from django.contrib import admin
from django import forms
from django.core.exceptions import ValidationError
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import Group as GroupAdmin
from .models.user import User
# from . import User, AnswerType, Answer, Course, GenQuestion, Outcome, Response, Section, Semester, StudentInSection


class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(
        label='Password confirmation', widget=forms.PasswordInput)

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise ValidationError('Passwords do not match')
        return password2

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ('pid', 'first_name', 'last_name',)


class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('pid', 'first_name', 'last_name',
                  'password', 'is_active', 'is_admin')


class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm

    list_display = ('pid', 'first_name', 'last_name', 'is_admin')
    list_filter = ['is_admin']
    fieldsets = (
        (None, {'fields': ('pid', 'password')}),
        ('Personal Info', {'fields': ('first_name', 'last_name')}),
        ('Permissions', {'fields': ('is_admin',)}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('pid', 'first_name', 'last_name', 'password1', 'password2'),
        }),
    )

    search_fields = ('pid',)
    ordering = ('pid',)
    filter_horizontal = ()


# Register your models here.
admin.site.register(User, UserAdmin)
admin.site.unregister(GroupAdmin)
# admin.site.register(AnswerType)
# admin.site.register(Answer)
# admin.site.register(Course)
# # admin.site.register(CSQuestion)
# # admin.site.register(EvalPeriod)
# admin.site.register(GenQuestion)
# # admin.site.register(Group)
# # admin.site.register(InstructorGroup)
# admin.site.register(Outcome)
# admin.site.register(Response)
# admin.site.register(Section)
# admin.site.register(Semester)
# # admin.site.register(Session)
# admin.site.register(StudentInSection)
