"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 15.12.20

"""
from getpass import getpass

from user.models import User
from django.contrib.auth.models import Group
from django.core.management import BaseCommand, call_command
from django.db import transaction

from konova.management.commands.setup_data import GROUPS_DATA, USER_NOTIFICATIONS_NAMES
from user.enums import UserNotificationEnum
from user.models import UserNotification

CREATED_TEMPLATE = "{} created"


class BaseKonovaCommand(BaseCommand):
    def handle(self, *args, **options):
        # Needs to be implemented in inheriting classes
        raise NotImplementedError

    def _break_line(self):
        """ Simply prints a line break

        Returns:

        """
        self.stdout.write("\n")

    def _write_warning(self, txt: str):
        self.stdout.write(
            self.style.WARNING(
                txt
            )
        )

    def _write_success(self, txt: str):
        self.stdout.write(
            self.style.SUCCESS(
                txt
            )
        )

    def _write_error(self, txt: str):
        self.stdout.write(
            self.style.ERROR(
                txt
            )
        )

    class Meta:
        abstract = True


class Command(BaseKonovaCommand):
    help = "Initializes database with basic data"

    def handle(self, *args, **options):
        try:
            with transaction.atomic():
                self._init_superuser()
                self._init_default_groups()
                self._init_user_notifications()
                self._init_codelists()
        except KeyboardInterrupt:
            self._break_line()
            exit(-1)

    def _init_superuser(self):
        """ Create a superuser by user prompt input

        Returns:

        """
        self._write_warning("--- Superuser ---")
        username = input("Superuser name: ")

        if User.objects.filter(username=username).exists():
            self._write_error("Superuser {} exists! Skip.".format(username))
            return

        pw = getpass("Password: ")
        pw_confirm = getpass("Confirm password : ")
        if pw != pw_confirm:
            self._write_error("Passwords did not match!")
            exit(-1)

        # Create superuser
        superuser = User()
        superuser.username = username
        superuser.is_superuser = True
        superuser.is_staff = True
        superuser.set_password(pw)
        superuser.save()
        self._write_success("Superuser {} created".format(username))
        self._break_line()

    def _init_default_groups(self):
        """ Creates the default groups for konova:
        * Group default
        * Group ZB (registration office employees)
        * Group ETS (conservation office employees)

        Returns:

        """
        self._write_warning("--- Groups ---")
        for group_data in GROUPS_DATA:
            name = group_data.get("name")
            Group.objects.get_or_create(
                name=name,
            )
            self._write_success(CREATED_TEMPLATE.format(name))

        self._break_line()

    def _init_user_notifications(self):
        """ Creates the default user notification triggers

        Returns:

        """
        self._write_warning("--- User Notifications ---")
        choices = UserNotificationEnum.as_choices(drop_empty_choice=True)
        for choice in choices:
            UserNotification.objects.get_or_create(
                id=choice[0],
                name=USER_NOTIFICATIONS_NAMES.get(choice[0], None),
            )
            self._write_success(CREATED_TEMPLATE.format(choice[0]))

        self._break_line()

    def _init_codelists(self):
        """ Calls the 'update_codelist' command found in codelist app

        Returns:

        """
        return call_command(
            'update_codelist'
        )
