# -*- coding: utf-8 -*-
import logging

from django.apps import AppConfig
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.signals import post_migrate

from ocyan.core.fender import config
from ocyan.core.signals import post_loaddemodata

from ocyan.plugin.django.management.commands.password import gen_password

logger = logging.getLogger(__name__)


def create_superuser():
    try:
        admin_user_name = config.get("django", "username", "superuser")
        admin_email = settings.DEFAULT_FROM_EMAIL
        User = get_user_model()
        if not User.objects.filter(username=admin_user_name).exists():
            User.objects.create_superuser(admin_user_name, admin_email, gen_password())
    except Exception as e:  # pylint: disable=W0703
        logger.exception(e)


# pylint: disable=unused-argument
def post_migrate_create_superuser(sender, app_config, **kwargs):
    "Make sure the superuser exists"
    if app_config.label == "auth":  # user model is ready to query
        create_superuser()


# pylint: disable=unused-argument
def post_loaddemodata_create_superuser(has_unloaded_fixtures, **kwargs):
    """
    The demo data plugin (when installed) undos the superuser creation from in our post_migrate_create_superuser
    receiver function. This receiver function will create it again once the demo data has been loaded.
    """
    if has_unloaded_fixtures:
        create_superuser()


class OcyanPluginDjangoAppConfig(AppConfig):
    name = "ocyan.plugin.django"
    label = "ocyan_plugin_django"

    def ready(self):
        post_migrate.connect(post_migrate_create_superuser)
        post_loaddemodata.connect(post_loaddemodata_create_superuser)
