# -*- coding: utf-8 -*-

from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned
from django.core.management.base import BaseCommand, CommandError

from pinax.notifications.models import NoticeType
import waffle

from mtp.apps.accounts.constants import (
    GROUPTYPE_BUSINESS_LEVEL,
    GROUPTYPE_BUSINESS_TARGET,
    GROUPTYPE_BUSINESS_TYPE,
    GROUPTYPE_BUSINESS_UNIT,
    GROUPTYPE_BUSINESS_ZONE,
    GROUPTYPE_INTERNAL,
    GROUPTYPE_JOB_NAME,
    GROUPTYPE_JOB_PROFILE,
    GROUPTYPE_JOB_TYPE,
    INTERNAL_GROUP_TRAINEE,
    INTERNAL_GROUP_TRAINER,
    INTERNAL_GROUP_WHOSWHO,
)
from mtp.apps.accounts.models import Group, GroupType, MTPUser
from mtp.apps.accounts.utils import init_user
from mtp.apps.brainstormers.constants import (
    ACTIVITY_IMAGE_SWOT, ACTIVITY_PREVIEW_BLANK, ACTIVITY_PREVIEW_SWOT
)
from mtp.apps.brainstormers.factories import BrainstormerActivityFactory
from mtp.apps.themes.constants import DEFAULT_THEME_NAME
from mtp.apps.themes.models import Theme

DEFAULT_PASSWORD = '123456'


def create_group(name, type_name):
    group_type, __ = GroupType.objects.get_or_create(name=type_name)
    group, created = Group.objects.get_or_create(name=name, type=group_type)
    if created:
        print("Creating group: '%s'." % name)
    else:
        print("Group '%s' already exists, skipping." % name)


def create_user(username, first_name, last_name, email, is_trainer):
    user, created = MTPUser.objects.get_or_create(
        username=username,
        defaults={
            'first_name': first_name,
            'last_name': last_name,
            'email': email,
        }
    )
    if created:
        init_user(user, DEFAULT_PASSWORD, None, is_trainer)
        if is_trainer:
            print("Creating trainer: '%s'." % username)
        else:
            print("Creating trainee: '%s'." % username)
    else:
        if user.is_staff:
            print("User '%s' already exists, and is a trainer." % username)
        else:
            print("User '%s' already exists, and is a trainee." % username)


def create_initial_brainstormer_activities():
    BrainstormerActivityFactory(
        name="Blank Board",
        preview=ACTIVITY_PREVIEW_BLANK,
    )
    BrainstormerActivityFactory(
        name="Swot",
        preview=ACTIVITY_PREVIEW_SWOT,
        image=ACTIVITY_IMAGE_SWOT,
    )


class Command(BaseCommand):
    args = ''
    help = "Populate the MTP database with generic initial data."

    def handle(self, *args, **options):
        if settings.INSTANCE_IS_SLAVE:
            raise CommandError(
                "A local server can't initialize data, please check the configuration."
            )

        # Create initial groups and group types.
        GroupType.objects.get_or_create(name=GROUPTYPE_BUSINESS_LEVEL)
        GroupType.objects.get_or_create(name=GROUPTYPE_BUSINESS_TARGET)
        GroupType.objects.get_or_create(name=GROUPTYPE_BUSINESS_TYPE)
        GroupType.objects.get_or_create(name=GROUPTYPE_BUSINESS_UNIT)
        GroupType.objects.get_or_create(name=GROUPTYPE_BUSINESS_ZONE)
        GroupType.objects.get_or_create(name=GROUPTYPE_JOB_NAME)
        GroupType.objects.get_or_create(name=GROUPTYPE_JOB_PROFILE)
        GroupType.objects.get_or_create(name=GROUPTYPE_JOB_TYPE)
        create_group(INTERNAL_GROUP_TRAINER, GROUPTYPE_INTERNAL)
        create_group(INTERNAL_GROUP_TRAINEE, GROUPTYPE_INTERNAL)
        create_group(INTERNAL_GROUP_WHOSWHO, GROUPTYPE_INTERNAL)

        # Create an initial trainer.
        create_user('formateur', 'Formateur', 'One', 'formateur@magency.fr', True)

        # Create an initial trainee.
        create_user('stagiaire', 'Stagiaire', 'One', 'stagiaire@magency.fr', False)

        # Create the default theme.
        default_theme = {
            'default': True,

            'color_first': "#823481",
            'color_second': "#d7d7d7",
            'color_item': "#ffffff",
            'color_selected_item': "#823481",
            'color_text_item': "#686868",
            'color_text_selected_item': "#ffffff",
            'color_text_quizz': "#ffffff",

            'background_color': "#f3f3f3",
            'background_color_diffusion': "#f3f3f3",

            'main': "#6b32bf",
            'main_lighter': "#b29dd2",
            'main_darker': "#2b134e",
            'complementary': "#45a49a",
            'clear': "#ffffff",
            'background': "#f3f3f3",

            'gray': "#d3d3d3",
            'gray_lighter': "#ededed",
            'gray_darker': "#505050",

            'text_on_main': "#ffffff",
            'text_on_main_lighter': "#000000",
            'text_on_main_darker': "#ffffff",
            'text_on_complementary': "#ffffff",
            'text_on_clear': "#000000",

            'accent_blue': "#7dd6da",
            'accent_green': "#a5de4f",
            'accent_yellow': "#fed201",
            'accent_pink': "#f56dc1",
            'accent_red': "#f26037",
            'accent_white': "#ffffff",

            'font_name': "HelveticaNeue",
            'font_bold_name': "HelveticaNeue-Bold",
            'font_thin_name': "HelveticaNeue-Light",
        }

        try:
            theme, created = Theme.objects.get_or_create(
                name=DEFAULT_THEME_NAME, defaults=default_theme
            )
        except MultipleObjectsReturned:
            created = False


        if created:
            print("Creating default theme.")
        else:
            print("Default theme already exists.")

        # Create the initial Waffle feature switches
        print ("Creating Waffle feature switches.")
        waffle.models.Switch.objects.get_or_create(
            name='enable_assessments',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_photostory',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_evaluation',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_training_locks',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_favorites_trainings_per_default',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_roleplay',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_translation',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_likes',
            defaults={'active': False}
        )
        waffle.models.Switch.objects.get_or_create(
            name='enable_surveys',
            defaults={'active': True}
        )

        create_initial_brainstormer_activities()

        # Notice types

        print("Creating Notice types.")

        NoticeType.create(
            "trainee_post_trainingsession",
            "Session content online",
            "Send to the trainee at the end of a training session"
        )
        NoticeType.create(
            "trainer_post_trainingsession",
            "Session content online",
            "Send to the trainer at the end of a training session"
        )
        NoticeType.create(
            "user_welcome",
            "Welcoming the user",
            "Send when a new user is registered across the system"
        )

        print("All done.")

        # TODO: This should be a fixture.
