from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# Register your models here.
from .models import *
from .forms import *

from django.db.models import Q
from django.utils.html import mark_safe
from django.utils.translation import gettext_lazy as _

admin.site.register(Company)
admin.site.register(AccessToken)

class ProfileInline(admin.StackedInline):
    model = Profile
    can_delete = False
    verbose_name_plural = 'Profiles'
    fk_name = 'user'
    fieldsets = (
        (None, {'fields': ('colorBlind', 'group', 'is_disclaimer_agreed',)}),
    )

class CustomUserAdmin(UserAdmin):

    inlines = (ProfileInline, )
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'get_colorBlind', 'get_membership')
    list_select_related = ('profile', )

    def get_fieldsets(self, request, obj=None):
        if request.path.find('/change/') != -1:
            return (
                (None, {'fields': ('username', 'password')}),
                (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
                (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'user_permissions')}),
                (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
            )
        else:
            return super(CustomUserAdmin, self).get_fieldsets(request, obj)

    def get_membership(self, instance):        
        if not hasattr(instance, 'profile'):
            return "None"
        return instance.profile.group
    get_membership.short_description = 'Membership'

    def get_colorBlind(self, instance):        
        if not hasattr(instance, 'profile'):
            return False
        return instance.profile.colorBlind
    get_colorBlind.boolean = True
    get_colorBlind.short_description = 'Colorblind Status'

    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(CustomUserAdmin, self).get_inline_instances(request, obj)

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

class PinIconAdmin(admin.ModelAdmin):

    search_fields = ['name']
    
    def pin_icon_image(self, obj):
        return mark_safe('<img src="{url}" width="{width}" height={height} />'.format(
            url = obj.icon.url,
            width='25px',
            height='41px',
            )
        )

    def get_list_display(self, request):
        return ['name','pin_icon_image']

admin.site.register(PinIcon, PinIconAdmin)

class IsDefaultCategoryFilter(admin.SimpleListFilter):
    title = 'Category Level'
    parameter_name = 'category_level'

    def lookups(self, request, model_admin):
        return (
            ('Default', 'Default categories'),
            ('Customer', 'Customer categories'),
        )

    def queryset(self, request, queryset):
        value = self.value()
        if value == 'Default':
            return queryset.filter(owner__isnull=True)
        elif value == 'Customer':
            return queryset.exclude(owner__isnull=True)
        return queryset

class CategoryAdmin(admin.ModelAdmin):

    search_fields = ['name']
    ordering = ['-owner']
    change_form_template = 'admin/webmap/category/category_change_form.html'
    
    def pin_icon_image(self, obj):
        return mark_safe('<img src="{url}" width="{width}" height={height} />'.format(
            url = obj.pin_icon.icon.url,
            width='25px',
            height='41px',
            )
        )

    def get_list_filter(self, request):
        if request.user.is_superuser:
            return [IsDefaultCategoryFilter]
        else:
            return []

    def get_list_display(self, request):
        if request.user.is_superuser:
            return ['name','pin_icon_image','owner','category_level']
        else:
            return ['name','pin_icon_image']

    def category_level(self, obj):
        if obj.owner is None:
            return 'Default category'
        else:
            return 'Customer category'

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(owner=request.user)

    def save_model(self, request, obj, form, change):
        if not request.user.is_superuser:
            obj.owner = request.user
        obj.save()

    def get_form(self, request, obj=None, **kwargs):
        if not request.user.is_superuser:
            self.fields = ['name', 'pin_icon',]
        else:
            self.fields = ['name', 'pin_icon', 'owner']
        return super(CategoryAdmin, self).get_form(request, obj, **kwargs)

admin.site.register(Category, CategoryAdmin)

class PopUpAlertAdmin(admin.ModelAdmin):
    list_display = ('title', 'start', 'end', 'msg')
    
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            return qs.none()
            
admin.site.register(PopUpAlert, PopUpAlertAdmin)

class FolderAdmin(admin.ModelAdmin):
    list_display = ('name', 'owner')
    search_fields = ['name']
    
    def get_list_filter(self, request):
        if request.user.is_superuser:
            return ['name']
        else:
            return []
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(owner=request.user)
    
    def save_model(self, request, obj, form, change):
        if not request.user.is_superuser:
            obj.owner = request.user
        obj.save()
    
    def get_form(self, request, obj=None, **kwargs):
        if not request.user.is_superuser:
            self.fields = ['name']
        else:
            self.fields = ['name', 'owner']
        return super(FolderAdmin, self).get_form(request, obj, **kwargs)

admin.site.register(Folder, FolderAdmin)

class PointAdmin(admin.ModelAdmin):
#    fields = ['location', 'longitude', 'latitude', 'user']
#    fieldsets = [
#        ('Location', {'fields': ['location', 'longitude', 'latitude']}),
#        (None, {'fields': ['user']})
#    ]
#    list_filter = ['user']
    search_fields = ['location']
    readonly_fields=('address', 'longitude', 'latitude')
    
    def get_list_display(self, request):
        if request.user.is_superuser:
            return ['location', 'address', 'longitude', 'latitude',
                    'category', 'user', 'folder',]
        else:
            return ['location', 'address', 'longitude', 'latitude',
                    'category', 'folder',]

    def get_list_filter(self, request):
        if request.user.is_superuser:
            return ['user']
        else:
            return []
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(user=request.user)
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "folder":
            if not request.user.is_superuser:
                kwargs["queryset"] = Folder.objects.filter(owner=request.user)
        if db_field.name == "category":
            if not request.user.is_superuser:
                kwargs["queryset"] = Category.objects.filter(Q(owner__isnull=True) | Q(owner=request.user)) # showing only default and own categories
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
    
    # disable managing for customer
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        formfield = super().formfield_for_dbfield(db_field, request, **kwargs)        

        if not request.user.is_superuser:
            formfield.widget.can_delete_related = False
            formfield.widget.can_change_related = False
            formfield.widget.can_add_related = False
        return formfield
    
    def get_form(self, request, obj=None, **kwargs):
        if not request.user.is_superuser:
            self.fields = ['category', 'location', 'address', 'latitude', 'longitude',
                           'folder', 'visible',]
        else:
            self.fields = ['category', 'location', 'address', 'user', 'active',
                           'latitude', 'longitude',
                           'visible', 'folder',]
        return super(PointAdmin, self).get_form(request, obj, **kwargs)
        
admin.site.register(Point, PointAdmin)

class BasemapAdmin(admin.ModelAdmin):
    list_display = ('name', 'tileURL', 'default')
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_authenticated:
            return qs
        return qs.get(default=True)

admin.site.register(Basemap, BasemapAdmin)

class CartoOverlayAdmin(admin.ModelAdmin):
    list_display = ('name', 'vizKey', 'legendTitle', 'legendData')
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_authenticated:
            return qs
        return qs.get(default=True)

admin.site.register(CartoOverlay, CartoOverlayAdmin)

# Admin site settings
admin.site.site_title = 'REIndicator settings'
admin.site.site_header = 'REIndicator settings'
admin.site.index_title = ''

