from wagtail.actions.copy_for_translation import ParentNotTranslatedError
from wagtail.models import Locale, Page

from books.models.module import Module
from books.models.topic import Topic

from core.logger import get_logger

logger = get_logger(__name__)


class AlreadyTranslatedException(Exception):
    pass


class PageDoesNotExistException(Exception):
    pass


def translate_page(page: Page, locale: Locale):
    logger.debug(f"translating page {page} for locale {locale}")
    translated_page = page.copy_for_translation(locale)
    revision = translated_page.latest_revision
    translated_page.publish(revision)
    return translated_page


# todo: write a test maybe
def convert_page_to_translation(page_model, slug: str, original_slug: str, language_code="en"):
    """
    Migrate a module and its children to a new locale and links it to
    its translation in the original locale.

    @param slug: the slug of the module to migrate
    @param original_slug: the slug of the module in the original locale
    """
    try:
        page = page_model.objects.get(slug=slug)
    except page_model.DoesNotExist:
        raise PageDoesNotExistException(slug)
    try:
        original = page_model.objects.get(slug=original_slug)
    except page_model.DoesNotExist:
        raise PageDoesNotExistException(original_slug)
    if original.translation_key == page.translation_key:
        raise AlreadyTranslatedException
    locale, _ = Locale.objects.get_or_create(language_code=language_code)
    logger.debug("Starting conversion")
    topic: Topic = page.get_parent()
    try:
        logger.debug("Getting existing topic translation")
        translated_topic = topic.get_translation(locale)
    except Page.DoesNotExist:
        logger.debug("Creating topic translation")
        try:
            translated_topic = translate_page(topic, locale)
        except ParentNotTranslatedError:
            # let's try to translate the parent page too
            translate_page(topic.get_parent(), locale)
            translated_topic = translate_page(topic, locale)

    page.locale = locale
    if original is not None:
        translation_key = original.translation_key
        page.translation_key = translation_key
    page.save()
    chapters = page.get_children()
    for chapter in chapters:
        chapter.locale = locale
        chapter.save()
        content_blocks = chapter.get_children()
        for content_block in content_blocks:
            content_block.locale = locale
            #content_block.save()

    logger.debug(f"moving {page} to {translated_topic}")
    page.move(translated_topic, "last-child")

    return f"Converted page {slug} to be the {language_code} translation of {original_slug}"


