# Generated by Django 2.1.9 on 2019-09-19 11:14

from django.conf import settings
from django.db import migrations

import logging
logger = logging.getLogger(__file__)


def create_title_extensions(apps, schema_editor):
    # ImageExtension = apps.get_model('djangocms_page_image', 'ImageExtension')
    # TeaserExtension = apps.get_model('djangocms_page_image', 'TeaserExtension')
    # Title = apps.get_model('cms', 'Title')

    # We don't use historic models at this point because we need special model methods
    from ..models import ImageExtension, TeaserExtension
    from cms.models import Title

    # The page extensions we're migrating naturally don't have a language assigned, thus we assume the
    # project's default language
    lang = getattr(settings, 'LANGUAGE_CODE')

    for image_extension in ImageExtension.objects.filter(public_extension__isnull=False):
        try:
            title_obj = Title.objects.get(
                page=image_extension.extended_object,
                language=lang
            )
        except Title.DoesNotExist:
            logger.info('Title object in default language could not be found for page "{}", skipping.'.format(
                image_extension.extended_object
            ))
            continue
        teaser_extension = TeaserExtension(
            extended_object=title_obj,
            image=image_extension.image,
            preview_image=image_extension.preview_image,
            teaser=image_extension.teaser,
            show_preview=image_extension.show_preview,
            extra_classes=image_extension.extra_classes
        )
        teaser_extension.save()
        teaser_extension.copy_to_public(
            title_obj.publisher_public,
            lang
        )
        logger.info('Teaser extension for title "{}" successfully created.'.format(title_obj))


class Migration(migrations.Migration):
    dependencies = [
        ('cms', '0017_pagetype'),
        ('djangocms_page_image', '0009_teaserextension'),
    ]

    operations = [
        migrations.RunPython(create_title_extensions, migrations.RunPython.noop),
    ]
