import wagtail_factories
from django.conf import settings
from django.core.management import call_command
from wagtail.models import Locale, Page, Site
from wagtail_localize.models import LocaleSynchronization

from vbv_lernwelt.core.admin import User
from vbv_lernwelt.course.consts import (
    COURSE_UK_TRAINING,
    COURSE_UK_TRAINING_FR,
    COURSE_UK_TRAINING_IT,
)
from vbv_lernwelt.course.creators.uk_course import (
    create_uk_circle_fahrzeug,
    create_uk_fr_circle_fahrzeug,
    create_uk_it_circle_fahrzeug,
)
from vbv_lernwelt.course.models import CoursePage
from vbv_lernwelt.learnpath.tests.learning_path_factories import (
    LearningPathFactory,
    TopicFactory,
)


def create_uk_training_learning_path(
    course_id=COURSE_UK_TRAINING, user=None, skip_locales=True
):
    if user is None:
        user = User.objects.get(username="info@iterativ.ch")

    site = Site.objects.filter(is_default_site=True).first()

    if not site:
        site = wagtail_factories.SiteFactory(is_default_site=True)

    if settings.APP_ENVIRONMENT == "development":
        site.port = 8000
        site.save()

    course_page = CoursePage.objects.get(course_id=course_id)
    lp = LearningPathFactory(
        title="Lernpfad",
        parent=course_page,
    )

    if course_id == COURSE_UK_TRAINING:
        TopicFactory(title="Training", is_visible=True, parent=lp)
        create_uk_circle_fahrzeug(lp)
    elif course_id == COURSE_UK_TRAINING_FR:
        TopicFactory(title="Training", is_visible=True, parent=lp)
        create_uk_fr_circle_fahrzeug(lp)
    elif course_id == COURSE_UK_TRAINING_IT:
        TopicFactory(title="Training", is_visible=True, parent=lp)
        create_uk_it_circle_fahrzeug(lp)

    # locales
    if not skip_locales:
        locale_de = Locale.objects.get(language_code="de-CH")
        locale_fr, _ = Locale.objects.get_or_create(language_code="fr-CH")
        LocaleSynchronization.objects.get_or_create(
            locale_id=locale_fr.id, sync_from_id=locale_de.id
        )
        locale_it, _ = Locale.objects.get_or_create(language_code="it-CH")
        LocaleSynchronization.objects.get_or_create(
            locale_id=locale_it.id, sync_from_id=locale_de.id
        )
        call_command("sync_locale_trees")

    # all pages belong to 'admin' by default
    Page.objects.update(owner=user)
