# 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
from django.utils.translation import get_language_info


class Migration(migrations.Migration):

    dependencies = [
        ("models", "7801_i18n_boolean_datatype"),
    ]

    sql = """
        UPDATE public.cards_x_nodes_x_widgets
        SET config =
            config ||
            jsonb_set(
                jsonb_set(
                    config,
                    '{{placeholder}}', json_build_object('{0}', config->>'placeholder')::jsonb, true
                ),
                '{{defaultValue}}',
                    json_build_object('{0}',
                        json_build_object('value', config->>'defaultValue', 'direction', '{1}'))::jsonb, true)
                 ||
            '{{"i18n_properties": ["placeholder"]}}'
        WHERE nodeid in (SELECT nodeid FROM nodes WHERE datatype = 'string');

        UPDATE public.widgets
        SET defaultconfig = '{{
            "width": "100%",
            "maxLength": null,
            "uneditable": false,
            "placeholder": {{
                "{0}": "Enter text"
            }},
            "defaultValue":  {{
                "{0}": {{"value": "", "direction":"{1}"}}
            }},
            "i18n_properties": ["placeholder"]}}'
        WHERE datatype = 'string';
    """.format(
        settings.LANGUAGE_CODE, "ltr" if not get_language_info(settings.LANGUAGE_CODE)["bidi"] else "rtl"
    )

    reverse_sql = """
        UPDATE public.cards_x_nodes_x_widgets
        SET config = config - 'i18n_properties' ||
        json_build_object('defaultValue', jsonb_extract_path(config, 'defaultValue', '{0}', 'value'))::jsonb ||
        json_build_object('placeholder', jsonb_extract_path(config, 'placeholder', '{0}'))::jsonb
        WHERE nodeid in (SELECT nodeid FROM nodes WHERE datatype = 'string');

        UPDATE public.widgets
        SET defaultconfig = '{{
            "width": "100%",
            "maxLength": null,
            "uneditable": false,
            "placeholder": "Enter text",
            "defaultValue": ""
        }}'
        WHERE datatype = 'string';
    """.format(
        settings.LANGUAGE_CODE
    )

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