from django.core.management import BaseCommand

from users.models import User, SchoolClass, Role, UserRole


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('first_name')
        parser.add_argument('last_name')
        parser.add_argument('email')

    def handle(self, *args, **options):
        first_name = options['first_name']
        last_name = options['last_name']
        email = options['email']
        self.stdout.write('Creating user {} {} with email {}'.format(first_name, last_name, email))
        try:
            school_class_name = 'Klasse {} {}'.format(first_name, last_name)

            user, created = User.objects.get_or_create(email=email, username=email)
            user.first_name = first_name
            user.last_name = last_name
            user.set_password(User.objects.make_random_password())
            user.save()

            self.stdout.write("Assigning teacher role")
            try:
                teacher = Role.objects.get(key='teacher')
            except Role.DoesNotExist:
                Role.objects.create_default_roles()
                teacher = Role.objects.get(key='teacher')
            UserRole.objects.get_or_create(user=user, role=teacher)

            school, _ = SchoolClass.objects.get_or_create(name=school_class_name)
            user.school_classes.add(school)

            self.stdout.write("")

        except Exception as e:
            self.stdout.write(e)
