# -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-11-29 07:26
from __future__ import unicode_literals

import re
import json
try:
    from html.parser import HTMLParser  # py3
except ImportError:
    from HTMLParser import HTMLParser  # py2
import warnings
from django.db import migrations
from djangocms_text_ckeditor.models import Text as TextModel


def _replace_text_body(old_body, input_pattern, output_tag, id_format):
    regex = re.compile(input_pattern)

    def _do_replace(match):
        before_id, plugin_id, after_id = match.groups()

        if not plugin_id:
            return ''

        bits = []

        if before_id:
            bits.append(before_id.strip())

        bits.append(id_format.format(plugin_id))

        if after_id:
            bits.append(after_id.strip())

        # By using .join() we ensure the correct
        # amount of spaces are used to separate the different
        # attributes.
        tag_attrs = ' '.join(bits)
        return output_tag.format(tag_attrs)

    new_body, count = regex.subn(_do_replace, old_body)
    return new_body, count


def forwards(apps, schema_editor):
    html_parser = HTMLParser()

    for element in TextModel.objects.all():
        if element.plugin_type != 'AcceptConditionPlugin':
            continue

        try:
            old_body = html_parser.unescape(json.loads(element.body).get('html_content'))
        except ValueError:
            continue
        new_body, count = _replace_text_body(
            old_body,
            input_pattern=r'<img ([^>]*)\bid="plugin_obj_(?P<pk>\d+)"([^>]*)/?>',
            output_tag='<cms-plugin {}></cms-plugin>',
            id_format='id="{}"'
        )
        # print("Convert Cascade Element {} -> Text:\n    {}".format(element.pk, new_body))
        if count >= 1:
            # Only update body if there were plugins in the text
            TextModel.objects.filter(pk=element.pk).update(body=new_body)


def backwards(apps, schema_editor):
    warnings.warn("Backward migration is not implemented yet")


class Migration(migrations.Migration):

    dependencies = [
        ('shop', '0003_glossary_fields'),
    ]

    operations = [
        migrations.RunSQL([("INSERT INTO djangocms_text_ckeditor_text (cmsplugin_ptr_id, body) "
                            "SELECT cmsplugin_ptr_id, glossary FROM cmsplugin_cascade_element "
                            "INNER JOIN cms_cmsplugin ON cmsplugin_ptr_id=id WHERE plugin_type='AcceptConditionFormPlugin';", None)]),
        migrations.RunSQL([("UPDATE cms_cmsplugin SET plugin_type='AcceptConditionPlugin' WHERE id IN ("
                            "SELECT id FROM (SELECT * FROM cms_cmsplugin) AS plugins WHERE plugin_type='AcceptConditionFormPlugin');", None)]),
        migrations.RunSQL([("DELETE FROM cmsplugin_cascade_element WHERE cmsplugin_ptr_id IN ("
                            "SELECT id FROM  cms_cmsplugin WHERE plugin_type='AcceptConditionPlugin');", None)]),
        migrations.RunPython(forwards, backwards),
    ]
