from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth.models import Group

from .models import User, GFGData, LeetcodeData, DailyGFGData, DailyLeetcodeData


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

    class Meta:
        model = User
        fields = ('email', 'name',)

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    disabled password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = User
        fields = ('email', 'password', 'name', 'is_staff', 'is_superuser')


class UserAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('name', 'email', 'is_active', 'handle_verified', 'is_superuser')
    list_filter = ('is_staff', 'is_active')
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('name', 'handle_verified', 'is_gfg')}),
        ('Permissions', {'fields': ('is_staff',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'name', 'password',),
        }),
    )
    search_fields = ('email', 'name')
    ordering = ('email',)
    filter_horizontal = ()


class GFGUserDataAdmin(admin.ModelAdmin):
    list_display = ['user', 'total_questions', 'coding_score']


class LeetcodeUserDataAdmin(admin.ModelAdmin):
    list_display = ['user', 'total_questions', 'points']


class DailyDataAdmin(admin.ModelAdmin):
    list_display = ['user', 'total_questions', 'easy', 'medium', 'hard', 'date']


admin.site.register(User, UserAdmin)
admin.site.register(GFGData, GFGUserDataAdmin)
admin.site.register(LeetcodeData, LeetcodeUserDataAdmin)
admin.site.register(DailyGFGData, DailyDataAdmin)
admin.site.register(DailyLeetcodeData, DailyDataAdmin)

admin.site.unregister(Group)
