# Generated by Django 3.2.11 on 2022-03-13 16:19

# -*- coding: utf-8 -*-
import json

import wagtail.core.blocks
import wagtail.core.fields
from django.core.serializers.json import DjangoJSONEncoder
from django.db import migrations
from wagtail.core.rich_text import RichText


def page_to_streamfield(page):
    changed = False
    if page.text and not page.content:
        page.content = [("text", RichText(page.text))]
        changed = True
    return page, changed


def pagerevision_to_streamfield(revision_data):
    changed = False
    body = revision_data.get("text")
    if body:
        try:
            json.loads(body)
        except ValueError:
            revision_data["content"] = json.dumps(
                [{"value": body, "type": "text"}], cls=DjangoJSONEncoder
            )
            changed = True
        else:
            # It's already valid JSON. Leave it.
            pass
    return revision_data, changed


def page_to_richtext(page):
    changed = False
    if page.content.raw_text is None:
        raw_text = "".join(
            [child.value.source for child in page.content if child.block_type == "text"]
        )
        page.text = raw_text
        changed = True
    return page, changed


def pagerevision_to_richtext(revision_data):
    changed = False
    body = revision_data.get("content", "definitely non-JSON string")
    if body:
        try:
            body_data = json.loads(body)
        except ValueError:
            # It's not apparently a StreamField. Leave it.
            pass
        else:
            raw_text = "".join(
                [child["value"] for child in body_data if child["type"] == "text"]
            )
            revision_data["text"] = raw_text
            changed = True
    return revision_data, changed


def convert(apps, schema_editor, page_converter, pagerevision_converter):
    UniwebArticlePage = apps.get_model("uniweb", "UniwebArticlePage")
    for page in UniwebArticlePage.objects.all():

        page, changed = page_converter(page)
        if changed:
            page.save()

        for revision in page.revisions.all():
            revision_data = json.loads(revision.content_json)
            revision_data, changed = pagerevision_converter(revision_data)
            if changed:
                revision.content_json = json.dumps(revision_data, cls=DjangoJSONEncoder)
                revision.save()


def convert_to_streamfield(apps, schema_editor):
    return convert(
        apps, schema_editor, page_to_streamfield, pagerevision_to_streamfield
    )


def convert_to_richtext(apps, schema_editor):
    return convert(apps, schema_editor, page_to_richtext, pagerevision_to_richtext)


class Migration(migrations.Migration):

    dependencies = [
        ("uniweb", "0021_alter_uniwebarticletag_tag"),
    ]

    operations = [
        migrations.AddField(
            model_name="uniwebarticlepage",
            name="content",
            field=wagtail.core.fields.StreamField(
                [
                    (
                        "text",
                        wagtail.core.blocks.RichTextBlock(
                            features=[
                                "h2",
                                "h3",
                                "h4",
                                "bold",
                                "italic",
                                "ol",
                                "ul",
                                "link",
                                "document-link",
                                "image",
                            ],
                            label="Textový editor",
                        ),
                    )
                ],
                blank=True,
                verbose_name="Článek",
            ),
        ),
        migrations.RunPython(
            convert_to_streamfield,
            convert_to_richtext,
        ),
        migrations.RemoveField(
            model_name="uniwebarticlepage",
            name="text",
        ),
    ]