from itertools import chain

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserChangeForm
from django.contrib.postgres.forms.array import SimpleArrayField
from django.contrib.postgres.utils import prefix_validation_error
from django.core.exceptions import ValidationError
from django.forms.fields import ChoiceField
from django.utils.translation import ugettext_lazy as _
from tasks.constants import IntroPopupType
from users.models import Apprentice, Mentor


class IntroMoviesSimpleArrayField(SimpleArrayField):
    def clean(self, value):
        if value:
            items = value.split(self.delimiter)
        else:
            items = []
        cleaned_data = []
        errors = []
        for index, item in enumerate(items):
            try:
                cleaned_data.append(int(self.base_field.clean(item)))
            except ValidationError as error:
                errors.append(prefix_validation_error(
                    error,
                    prefix=self.error_messages['item_invalid'],
                    code='item_invalid',
                    params={'nth': index},
                ))
                cleaned_data.append(None)
            else:
                errors.append(None)
        errors = list(filter(None, errors))
        if errors:
            raise ValidationError(list(chain.from_iterable(errors)))
        return cleaned_data


class ApprenticeAdminForm(UserChangeForm):
    intro_videos = IntroMoviesSimpleArrayField(base_field=ChoiceField(choices=IntroPopupType.choices))


class ApprenticeAdmin(UserAdmin):
    form = ApprenticeAdminForm
    fieldsets = (
        (None, {'fields': ('username', 'password', 'activation_key', 'email', 'is_active', 'intro_videos')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2'),
        }),
    )
    list_display = ('username', 'email', 'is_active', 'activation_key')
    list_filter = ('is_active',)
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)


class MentorAdmin(UserAdmin):
    pass


admin.site.register(Apprentice, ApprenticeAdmin)
admin.site.register(Mentor, MentorAdmin)
