from .models import SchoolClassMember, UserSetting, User


# This code was made for a support case where some users had invalid user settings.
def validate_user_setting(user_setting, dry_run=True):

    try:
        SchoolClassMember.objects.get(user=user_setting.user, school_class=user_setting.selected_class)

    # Test for the invalid user settings and delete them (user settings are gereated automatically)
    except SchoolClassMember.DoesNotExist as e:
        print(e)
        print(f"invalid user setting:      {user_setting.user.email} {user_setting.user.selected_class}")
        if not dry_run:
            user_id = user_setting.user.id
            try:
                del user_setting.user.selected_class
            except AttributeError:
                pass

            user_setting.delete()
            user = User.objects.get(id=user_id)

            print(f"New user setting:         {user.email} {user.selected_class}\n")

    # Errors with SchoolClassMember.MultipleObjectsReturned
    # A bug created duplicates in the database. This code deletes the duplicates.
    except SchoolClassMember.MultipleObjectsReturned as e:
        print(e)
        count = 0
        for member in SchoolClassMember.objects.filter(user=user_setting.user):
            print(f"Multiple SchoolClassMembers for user {count}: {member.id} {member.user.email}: {member.school_class.name} {member.active}")
            if count >=1:
                print("delete")
                if not dry_run:
                    member.delete()
            count += 1
        print("\n")

def validate_user_settings(dry_run=True):
    for user_setting in UserSetting.objects.all():
        validate_user_setting(user_setting, dry_run=dry_run)
