# coding=utf-8
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from BaseModels.admin_utils import *
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _

from AuthApp.models import *

from django.contrib.auth.models import Group
from django.db import models
from django.contrib.admin.models import LogEntry

from django.db.models import F, Value as V
from django.db.models.functions import Concat

from django.contrib.auth.admin import GroupAdmin as BaseGroupAdmin
from django.contrib.auth.models import Group
from django.contrib.admin import SimpleListFilter


class LogEntryAdmin(admin.ModelAdmin):
    # pass
    list_display = (
    '__str__', 'action_time', 'user', 'content_type', 'object_id', 'object_repr', 'action_flag', 'change_message')
    list_filter = ('content_type', 'action_flag')
    search_fields = ['user__username', 'change_message', 'object_id', 'object_repr']
    date_hierarchy = 'action_time'

    def has_delete_permission(self, request, obj=None):
        return False


admin.site.register(LogEntry, LogEntryAdmin)

# class Admin_ProfileInline(admin.StackedInline):
    # fieldsets = (
    #     (None, {
    #         'classes': ['wide'],
    #         'fields': (
    #             ('enable',),
    #             ('regions',),
    #             ('company_obj', 'office', 'company_position', 'departament'),
    #             ('delivery_address'),
    #             ('discount',),
    #             ('work_start_D', 'work_finish_D'),
    #             ('days_to_order_cancellation_default', 'days_to_pay_default', 'pay_terms'),
    #             ('authMailCode', 'document_sign_person'),
    #             ('birthdate'),
    #             'comment', 'creator'
    #         )
    #     }),
    #     ('Дополнительно', {
    #         'classes': ['wide'],
    #         'fields': (
    #             ('connected_mailings',),
    #             ('mailing_sets', 'json_data', 'sync_data')
    #         )
    #     }),
    #     ('1С', {
    #         'classes': ['wide'],
    #         'fields': (
    #             ('id_1s', 'name',),
    #         )
    #     }),
    # )
    #
    # model = UserProfile
    # can_delete = False
    # extra = 1
    # fk_name = 'user'
    #
    # filter_horizontal = ['regions', 'connected_mailings']
    # raw_id_fields = ("company_obj", 'office')
    # verbose_name_plural = _(u'Профиль пользователя')
    #
    # list_display = ['company_obj', 'office', 'company_position', 'departament', 'creator']
    # readonly_fields = ['creator', ]





# Define a new User admin
class Admin_User(UserAdmin):
    pass
    # def user_groups(self, obj):
    #     return ' \ '.join(obj.groups.all().values_list('name', flat=True))
    #
    # user_groups.short_description = u'Группы'
    #
    # def last_web_request(self, obj):
    #     return obj.user_profile.last_web_request
    #
    # last_web_request.short_description = u'Последний запрос'

    # def profile_enable(self, obj):
    #     if obj.user_profile.enable:
    #         return '+'
    #     else:
    #         return '-'
    #
    # profile_enable.short_description = u'Включен'

    # fieldsets = (
    #     (None, {
    #         'classes': ['wide'],
    #         'fields': (
    #             ('username', 'password'),
    #             ('first_name', 'last_name', 'email'),
    #             ('is_active', 'is_staff', 'is_superuser'),
    #             ('groups', 'user_permissions'),
    #             ('last_login', 'date_joined'),
    #             # ('username', 'first_name', 'last_name'),
    #             # ('password'),
    #             # ('email', 'is_active'),
    #             # ('is_staff')
    #         )
    #     }),
    #
    # )

    save_on_top = True

    # list_display = ['id', 'profile_enable', 'last_name', 'first_name', 'email', 'last_web_request', 'is_staff',
    #                 'is_active', 'user_groups']
    # list_editable = ['is_staff', 'is_active']
    # list_display_links = ['first_name', 'last_name', 'email']
    # search_fields = ['first_name', 'last_name', 'email']
    #
    # inlines = (Admin_ProfileInline,)
    # actions = ['del_all_temp_users', ]
    #
    # ordering = ['is_staff', 'last_name', 'first_name']
    #
    # def del_all_temp_users(modeladmin, request, queryset):
    #     queryset.filter(mipp_user__temporary_user=True).delete()
    #
    # del_all_temp_users.short_description = _(u'Удалить всех временных пользователей')


# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, Admin_User)


class Admin_UserProfile(Admin_BaseIconModel):
    pass
    # def get_list_filter(self, request):
    #     res = super(Admin_UserProfile, self).get_list_filter(request)
    #     user_groups = request.user.groups.all().values_list('name', flat=True)
    #     if request.user.is_superuser or 'Отдел продаж: Начальник отдела продаж' in user_groups or 'Маркетинг: Маркетолог' in user_groups:
    #         return res
    #
    #     return []
    #
    # def get_queryset(self, request):
    #     user_groups = request.user.groups.all().values_list('name', flat=True)
    #     if request.user.is_superuser or 'Отдел продаж: Начальник отдела продаж' in user_groups or 'Маркетинг: Маркетолог' in user_groups:
    #         return UserProfile.objects.all()
    #
    #     companies_ids = request.user.companies_for_manager.all().values_list('id', flat=True)
    #     queryset = UserProfile.objects.filter(
    #         company_obj__id__in=companies_ids
    #         # ).annotate(
    #         #     lead_source = F('company_obj__lead_source')
    #     )
    #     return queryset
    #
    # def get_list_display_links(self, request, list_display):
    #     res = super(Admin_UserProfile, self).get_list_display_links(request, list_display)
    #     if not request.user.is_superuser:  # and not request.user.has_perm('AuthApp.change_userprofile'):
    #         return None
    #     return res
    #
    # def get_changelist_instance(self, request):
    #     if not request.user.is_superuser:  # and not request.user.has_perm('AuthApp.change_userprofile'):
    #         self.list_editable = ['birthdate']
    #     return super(Admin_UserProfile, self).get_changelist_instance(request)
    #
    # def user_name(self, obj):
    #     return '{0} {1}'.format(obj.user.last_name, obj.user.first_name)
    #
    # user_name.short_description = u'Имя'
    #
    # def lead_source(self, obj):
    #     res = None
    #     if obj.company_obj:
    #         res = obj.company_obj.lead_source
    #     if not res:
    #         res = '-'
    #     else:
    #         res = obj.company_obj.get_lead_source_display()
    #     return res
    #
    # lead_source.short_description = 'Источник'
    # lead_source.admin_order_field = 'company_obj__lead_source'
    #
    # def manager(self, obj):
    #     if not obj.company_obj or not obj.company_obj.manager_obj:
    #         return '-'
    #
    #     return '{0}'.format(obj.company_obj.manager_obj.get_full_name())
    #
    # manager.short_description = u'Менеджер'
    #
    # fieldsets = (
    #     (None, {
    #         'classes': ['wide'],
    #         'fields': (
    #             'user', 'enable', 'account_type',
    #             ('discount',),
    #             ('work_start_D', 'work_finish_D'),
    #             ('company_obj', 'company', 'office', 'company_position', 'departament'),
    #             ('delivery_address'),
    #             ('days_to_order_cancellation_default', 'days_to_pay_default', 'pay_terms'),
    #             ('authMailCode', 'document_sign_person'),
    #             ('birthdate'),
    #             ('connected_mailings',),
    #             'creator'
    #         )
    #     }),
    #     ('1С', {
    #         'classes': ['wide'],
    #         'fields': (
    #             ('id_1s', 'name',),
    #         )
    #     }),
    # )
    #
    # save_on_top = True
    #
    # list_display = [
    #     # 'user__last_name', 'user__first_name', 'user__email', 'user__is_staff', 'user__is_active',
    #     'id', 'user_name', 'user', 'enable', 'birthdate', 'lead_source', 'manager',
    #     'company_obj', 'office', 'company_position', 'departament', 'account_type', 'modifiedDT', 'createDT'
    # ]
    # list_editable = ['enable', 'birthdate']
    # list_display_links = ['id', ]  # 'user__last_name', 'user__first_name']
    # search_fields = [
    #     'id', 'user__last_name', 'user__first_name', 'user__email', 'company_obj__name', 'company_position',
    #     'departament',
    #     'company_obj', 'company_obj__manager_obj'
    # ]  # 'user__last_name', 'user__first_name', 'user__email']
    #
    # list_filter = ['company_obj__lead_source', ManagersFilter, 'account_type']
    #
    # filter_horizontal = ['connected_mailings']
    # # raw_id_fields = ("favourites",)
    # verbose_name_plural = _(u'Профиль пользователя')


admin.site.register(UserProfile, Admin_UserProfile)
