import os
import random
import shutil
from uuid import uuid1

import wagtail_factories
from django.conf import settings
from django.core import management
from django.core.management import BaseCommand
from django.db import connection
from wagtail.core.models import Page

from books.factories import BookFactory, TopicFactory, ModuleFactory, ChapterFactory, ContentBlockFactory
from core.factories import UserFactory
from objectives.factories import ObjectiveGroupFactory, ObjectiveFactory
from users.services import create_users, create_student

from .data.module_data import data
from .data.user_data import user_data


class Command(BaseCommand):

    def ensure_clean_dir(self, folder):
        path = os.path.join(settings.MEDIA_ROOT, folder)
        if os.path.exists(path):
            shutil.rmtree(path)
        if not os.path.exists(path):
            os.makedirs(path)

    def filter_data(self, input_data, filter_keyword):
        filters = [filter_keyword] if not isinstance(filter_keyword, list) else filter_keyword
        return {k: v for (k, v) in input_data.items() if not (k in filters)}

    def handle(self, *args, **options):
        with connection.cursor() as cursor:
            cursor.execute("DROP SCHEMA IF EXISTS public CASCADE;")
            cursor.execute(
                "CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION {};".format(settings.DATABASES['default']['USER']))
            cursor.execute("GRANT ALL ON SCHEMA public TO {};".format(settings.DATABASES['default']['USER']))
        management.call_command('migrate', verbosity=0, interactive=False)

        self.ensure_clean_dir('images')
        self.ensure_clean_dir('original_images')
        self.ensure_clean_dir('documents')

        site = wagtail_factories.SiteFactory.create(is_default_site=True)

        Page.objects.get(title='Root').delete()

        UserFactory(
            username='test',
            is_staff=True,
            is_superuser=True,
            first_name='Nicol',
            last_name='Bolas',
            onboarding_visited=True
        )

        create_users(user_data)

        # create student without class
        create_student(
            username='hansli',
            first_name='Hansli',
            last_name='Alleini'
        )

        for book_idx, book_data in enumerate(data):
            book = BookFactory.create(parent=site.root_page, **self.filter_data(book_data, 'topics'))

            default_topics = [{} for _ in range(0, random.randint(5, 8))]
            topics_data = book_data.get('topics', default_topics)

            for topic_idx, topic_data in enumerate(topics_data):
                topic = TopicFactory.create(parent=book, **self.filter_data(topic_data, 'modules'))

                default_modules = [{} for _ in range(0, random.randint(3, 6))]
                modules_data = topic_data.get('modules', default_modules)

                for module_idx, module_data in enumerate(modules_data):
                    module = ModuleFactory.create(parent=topic,
                                                  **self.filter_data(module_data, ['objective_groups', 'chapters']))

                    default_objective_groups = [{} for _ in range(0, 2)]
                    objective_group_data = module_data.get('objective_groups', default_objective_groups)

                    for objective_group_idx, objective_group_entry in enumerate(objective_group_data):
                        factory_params = self.filter_data(objective_group_entry, 'objectives')
                        objective_group = ObjectiveGroupFactory.create(module=module,
                                                                       
                                                                       **factory_params)

                        default_objectives = [{} for _ in range(0, 4)]
                        objectives_data = objective_group_entry.get('objectives', default_objectives)

                        for objective_idx, objective_data in enumerate(objectives_data):
                            ObjectiveFactory.create(group=objective_group, **objective_data)

                    default_chapters = [{} for _ in range(0, 2)]
                    chapters_data = module_data.get('chapters', default_chapters)

                    for chapter_idx, chapter_data in enumerate(chapters_data):
                        chapter = ChapterFactory.create(parent=module,
                                                        **self.filter_data(chapter_data, 'content_blocks'))

                        default_content_blocks = [{} for _ in range(0, 4)]
                        content_blocks_data = chapter_data.get('content_blocks', default_content_blocks)

                        for content_block_idx, content_block_data in enumerate(content_blocks_data):
                            # ContentBlockFactory.create(parent=chapter, **self.filter_data(content_block_data, 'contents'))
                            ContentBlockFactory.create(parent=chapter, module=module, slug=f'{uuid1()}', **content_block_data)

        # now create all and rooms
        management.call_command('dummy_rooms', verbosity=0)
        management.call_command('dummy_news', verbosity=0)

