# -*- coding: utf-8 -*-
from __future__ import absolute_import

from django.contrib import admin
from django.conf import settings
from django.contrib import admin
from django.contrib import messages
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from transliterate import translit
from unidecode import unidecode

from app.tasks.hall_of_fame import generate
from core import models
from core.admin import filters


@admin.register(models.Reward)
class RewardAdmin(admin.ModelAdmin):
    actions = ['remove_award_bonus', 'set_default_product']
    list_display = ('vulnerability_type',
                    'payment_created',
                    'product',
                    'get_reporter_safe',
                    'user_uid',
                    'protocol')
    list_filter = ('department',
                   'product',
                   'status',
                   'vulnerability_type',
                   filters.RewardReporterLinkFilter,
                   filters.HasAwardBonus)
    readonly_fields = ['award_bonus', 'payment_created']
    search_fields = ['user_login', 'user_uid']

    def remove_award_bonus(self, request, queryset):
        disconnected_awards = queryset.update(award_bonus=None)
        self.message_user(
            request, '%s awards were disconnected' % disconnected_awards)

    def set_default_product(self, request, queryset):
        processed = dict()
        departments = dict(models.Reward.DEPARTMENTS)
        for reward in queryset:
            financial_unit_acronym = departments[reward.department]
            reward.product = models.Product.objects.filter(
                financial_unit__acronym=financial_unit_acronym).first()
            reward.save()
            processed[financial_unit_acronym] = processed.setdefault(financial_unit_acronym, 0) + 1
        for department, counter in processed.items():
            self.message_user(
                request, '%s rewards bound to %s' % (counter, department))


@admin.register(models.Reporter)
class ReporterAdmin(admin.ModelAdmin):
    list_display = ('uid', 'actual_payment_info')
    list_filter = ('payment_info__is_actual',
                   filters.ReporterRewardsFilter)
    search_fields = ['uid', 'username', 'email', 'contact_email']

    def actual_payment_info(self, obj):
        return obj.payment_info.is_actual


@admin.register(models.PaymentInfo)
class PaymentInfoAdmin(admin.ModelAdmin):
    actions = ['clear_ru_fio', 'clear_account_holder']
    list_display = ('reporter', 'ru_fio', 'account_holder')

    def clear_ru_fio(self, request, queryset):
        for profile in queryset.all():
            ru_fio = profile.ru_fio
            new_ru_fio = translit(unidecode(ru_fio), 'ru')
            if ru_fio != new_ru_fio:
                profile.ru_fio = new_ru_fio
                profile.save()
                self.message_user(
                    request,
                    _('Change: %(ru_fio)s -> %(new_ru_fio)s')
                    % {'old': ru_fio, 'new': new_ru_fio})
        self.message_user(request, _('Cyrillic transliteration complete'))
    clear_ru_fio.short_description = _('Clear ru_fio')

    def clear_account_holder(self, request, queryset):
        for profile in queryset.all():
            full_name = profile.account_holder
            new_full_name = unidecode(full_name)
            if full_name != new_full_name:
                profile.account_holder = new_full_name
                profile.save()
                self.message_user(
                    request,
                    _('Change: %(old)s -> %(new)s')
                    % {'old': full_name, 'new': new_full_name})
        self.message_user(request, _('Latin transliteration complete'))
    clear_account_holder.short_description = _('Clear account_holder')


@admin.register(models.List)
class ListAdmin(admin.ModelAdmin):
    actions = ['generate_hall_of_fame']

    def generate_hall_of_fame(self, request, queryset):
        for hall_of_fame_group in queryset:
            members_added = generate(
                hall_of_fame_group.year, hall_of_fame_group.month)
            self.message_user(
                request,
                '%s reporters added to %s' % (members_added, hall_of_fame_group))


@admin.register(models.Item)
class ItemAdmin(admin.ModelAdmin):
    list_filter = [filters.DuplicateMembership]


@admin.register(models.Badge)
class BadgeAdmin(admin.ModelAdmin):
    list_display = ['name_en', 'trigger', 'check_interval']
    list_filter = ['is_automatic', 'is_active']


@admin.register(models.UserBadge)
class UserBadgeAdmin(admin.ModelAdmin):
    list_display = ['badge', 'user', 'activated', 'deactivated']


@admin.register(models.Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = ['title', 'financial_unit', 'scope']


@admin.register(models.ProductScope)
class ProductScopeAdmin(admin.ModelAdmin):
    list_display = ['title']


@admin.register(models.EditablePage)
class EditablePageAdmin(admin.ModelAdmin):
    list_display = ['slug']


@admin.register(models.PageTranslation)
class PageTranslationAdmin(admin.ModelAdmin):
    list_display = ['page_slug', 'status']


@admin.register(models.Responsible)
class ResponsibleAdmin(admin.ModelAdmin):
    list_display = ['staff_username', 'role', 'name']
