# Generated by Django 2.2.13 on 2021-03-19 20:17
from arches.app.models.fields.i18n import I18n_JSONField
from django.db import migrations
from django.conf import settings


class Migration(migrations.Migration):

    dependencies = [
        ("models", "7899_i18n_graph_model_updates"),
    ]

    sql = """
        UPDATE public.nodes
        SET config = jsonb_set(jsonb_set(config, '{{trueLabel}}',
            json_build_object('{0}', config->>'trueLabel')::jsonb, true), '{{falseLabel}}',
            json_build_object('{0}', config->>'falseLabel')::jsonb, true) ||
            '{{"i18n_properties": ["trueLabel", "falseLabel"]}}'
        WHERE datatype = 'boolean';

        UPDATE widgets
        SET defaultconfig = defaultconfig ||
            json_build_object('subtitle', jsonb_build_object('{0}', jsonb_extract_path(defaultconfig, 'subtitle')))::jsonb
        WHERE datatype = 'boolean' AND defaultconfig ? 'subtitle';

        UPDATE public.d_data_types
        SET defaultconfig = jsonb_set(jsonb_set(defaultconfig, '{{trueLabel}}',
            json_build_object('{0}', defaultconfig->>'trueLabel')::jsonb, true), '{{falseLabel}}',
            json_build_object('{0}', defaultconfig->>'falseLabel')::jsonb, true) ||
            '{{"i18n_properties": ["trueLabel", "falseLabel"]}}'
        WHERE datatype = 'boolean';
    """.format(
        settings.LANGUAGE_CODE
    )

    reverse_sql = """
        UPDATE nodes
        SET config = config - 'i18n_properties' ||
            json_build_object('trueLabel', jsonb_extract_path(config, 'trueLabel', '{0}'))::jsonb ||
            json_build_object('falseLabel', jsonb_extract_path(config, 'falseLabel', '{0}'))::jsonb
        WHERE datatype = 'boolean';

        UPDATE widgets
        SET defaultconfig = defaultconfig ||
            json_build_object('subtitle', jsonb_extract_path(defaultconfig, 'subtitle', '{0}'))::jsonb
        WHERE datatype = 'boolean' AND defaultconfig ? 'subtitle';

        UPDATE public.d_data_types
        SET defaultconfig = defaultconfig - 'i18n_properties' ||
            json_build_object('trueLabel', jsonb_extract_path(defaultconfig, 'trueLabel', '{0}'))::jsonb ||
            json_build_object('falseLabel', jsonb_extract_path(defaultconfig, 'falseLabel', '{0}'))::jsonb
        WHERE datatype = 'boolean';

    """.format(
        settings.LANGUAGE_CODE
    )

    operations = [
        migrations.RunSQL(sql, reverse_sql),
        migrations.AlterField(
            model_name="node",
            name="config",
            field=I18n_JSONField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name="cardxnodexwidget",
            name="config",
            field=I18n_JSONField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name="ddatatype",
            name="defaultconfig",
            field=I18n_JSONField(blank=True, null=True),
        ),
    ]
