from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User, Permission
from rest_framework.authtoken.models import Token


class Command(BaseCommand):
    user_name = "sahkopiikki"
    password = User.objects.make_random_password()

    def handle(self, *args, **options):
        if User.objects.filter(username=self.user_name).exists():
            self.stdout.write("Sahkopiikki user already exists. Skipping.")
            user = User.objects.get(username=self.user_name)
            token = Token.objects.get(user=user)
            self.stdout.write("Token: {}".format(token))
            return

        u = User(username=self.user_name)
        u.set_password(self.password)

        u.save()

        permission = Permission.objects.get(codename='check_by_email')
        u.user_permissions.add(permission)

        token = Token.objects.create(user=u)

        self.stdout.write("Created sahkopiikki user '{}' with password '{}' and token '{}'.".format(
            self.user_name, self.password, token
        ))
