# 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", "6458_language"),
    ]

    sql = """
        CREATE OR REPLACE FUNCTION __arches_i18n_update_jsonb_array(i18n_property text, incoming_jsonb jsonb, current_jsonb jsonb, lang text)
        RETURNS jsonb
        LANGUAGE plpgsql AS $$

        -- see the migration 7805_i18n_domain_datatype for an example of how to run a test of this function
        
        DECLARE
        id_property_name text := 'id';
        path_to_array text := (string_to_array(i18n_property, '.'))[1];
        text_property_name text := (string_to_array(i18n_property, '.'))[2];
        elements jsonb := '[]';
        j record;
        domain_id text;
        val jsonb;
        res jsonb;
        x jsonb;
        ret jsonb;
        dynsql text;
        
        BEGIN
        --RAISE NOTICE '%', path_to_array;
        --RAISE NOTICE '%', (SELECT jsonb_extract_path(incoming_jsonb, path_to_array));
        
        FOR j IN (SELECT jsonb_array_elements(incoming_jsonb->path_to_array) element) LOOP
            --RAISE NOTICE '-------';
            domain_id = jsonb_extract_path_text(j.element::jsonb, id_property_name);
            --RAISE NOTICE '%', domain_id;
            
            --val := (SELECT items.text
            --    FROM jsonb_to_recordset(current_jsonb -> path_to_array) as items(text text, id text)
            --    WHERE items.id = domain_id);
            --RAISE NOTICE 'val1: %', val;
            
            dynsql = format('SELECT items.%1$I
                FROM jsonb_to_recordset(%2$L::jsonb -> %3$L::text) as items(%1$s text, %4$s text)
                WHERE items.%4$s = %5$L', 
                text_property_name, current_jsonb, path_to_array, id_property_name, domain_id);
            EXECUTE dynsql INTO val;
            --RAISE NOTICE '%', dynsql;
            --RAISE NOTICE 'val: %', val;
            
            IF jsonb_typeof(jsonb_extract_path(j.element, text_property_name)) = 'object' THEN
				res = jsonb_extract_path(j.element, text_property_name);
			ELSE
            	res = jsonb_build_object(lang, jsonb_extract_path(j.element, text_property_name));
            END IF;
            --RAISE NOTICE '%', res;
            
            IF val IS NOT NULL THEN
            res := val || res;
            --RAISE NOTICE '%', res;
            END IF;
            
            x := jsonb_set(j.element::jsonb, ARRAY[text_property_name], res);
            --RAISE NOTICE 'x: %', x;
            
            elements := jsonb_insert(elements, ARRAY['0'], x);
        END LOOP;
        
        --RAISE NOTICE '%', elements;
        ret = jsonb_set(current_jsonb, ARRAY[path_to_array], elements);
        --RAISE NOTICE '%', ret;
        RETURN ret;
        END;
        $$;


        CREATE OR REPLACE FUNCTION __arches_i18n_strip_jsonb_array(i18n_property text, incoming_jsonb jsonb, lang text)
        RETURNS jsonb
        LANGUAGE plpgsql AS $$

        -- see the migration 7805_i18n_domain_datatype for an example of how to run a test of this function

        DECLARE
        path_to_array text := (string_to_array(i18n_property, '.'))[1];
        inner_property text := (string_to_array(i18n_property, '.'))[2];
        elements jsonb := '[]';
        j record;
        extracted_text_at_lang jsonb;
        new_option_value jsonb;
        ret jsonb;
        BEGIN
        --RAISE NOTICE '%', path_to_array;
        --RAISE NOTICE '%', (select jsonb_extract_path(incoming_jsonb, path_to_array));
        
        FOR j IN (SELECT jsonb_array_elements(incoming_jsonb->path_to_array) element) LOOP
            --RAISE NOTICE '------';
            --RAISE NOTICE '%', j;
            extracted_text_at_lang = jsonb_extract_path(jsonb_extract_path(j.element, inner_property), lang);
            --RAISE NOTICE 'extracted text: %', extracted_text_at_lang;
            new_option_value := jsonb_set(j.element::jsonb, array[inner_property], extracted_text_at_lang);
            --RAISE NOTICE 'new option value: %', new_option_value;
            elements := jsonb_insert(elements, array['0'], new_option_value);

        END LOOP;
        --RAISE NOTICE '-----';
        ret = jsonb_set('{{}}'::jsonb, array[path_to_array], elements);
        --RAISE NOTICE 'final value: %', ret;
        RETURN ret;
        END;
        $$;


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

        UPDATE public.widgets
        SET defaultconfig = defaultconfig ||
        '{{"i18n_properties": ["placeholder"]}}'
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';

        UPDATE public.d_data_types
        SET defaultconfig = defaultconfig ||
        '{{"i18n_config": {{"fn":"arches.app.datatypes.datatypes.DomainDataType"}}}}'
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';

        UPDATE public.nodes
        SET config=__arches_i18n_update_jsonb_array('options.text'::text, config, '{{}}'::jsonb, '{0}'::text) || 
        '{{"i18n_config": {{"fn":"arches.app.datatypes.datatypes.DomainDataType"}}}}'
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';
    """.format(
        settings.LANGUAGE_CODE
    )

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

        UPDATE public.widgets
        SET defaultconfig = defaultconfig - 'i18n_properties'
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';

        UPDATE public.d_data_types
        SET defaultconfig = defaultconfig - 'i18n_config'
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';

        UPDATE public.nodes
        SET config= config - 'i18n_config' ||
        __arches_i18n_strip_jsonb_array('options.text'::text, config, '{0}'::text)
        WHERE datatype = 'domain-value' OR datatype = 'domain-value-list';

        DROP FUNCTION IF EXISTS __arches_i18n_update_jsonb_array;
        DROP FUNCTION IF EXISTS __arches_i18n_strip_jsonb_array;
    """.format(
        settings.LANGUAGE_CODE
    )

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


# -----------------------------------------------------------------------------
# -- This is a test that calls the function "__arches_i18n_update_jsonb_array"
# -- and should return w/o failing
# do $body$
# declare
# current_jsonb_old jsonb := '{
#     "options": [
#         {
#             "id": "cf18b6bd-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "tostada.test"},
#             "selected": false
#         },
#         {
#             "id": "aa18b6bd-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "burrito"},
#             "selected": false
#         },
#         {
#             "id": "bbbbbbbb-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "lager"},
#             "selected": false
#         }
#     ]
# }';
# incoming_jsonb_old jsonb := '{
#     "options": [
#         {
#             "id": "cf18b6bd-bb7b-4a51-aeb7-717aeb67e759",
#             "text": "taco",
#             "selected": false
#         },
#         {
#             "id": "3d7d6c14-354f-4f54-adbb-2800625b57e5",
#             "text": "porsche",
#             "selected": false
#         },
#         {
#             "id": "bbbbbbbb-bb7b-4a51-aeb7-717aeb67e759",
#             "text": "hazy ipa",
#             "selected": false
#         }
#     ]
# }';
# lang text := 'es';
# begin
# perform __arches_i18n_update_jsonb_array('options.text',incoming_jsonb_old, current_jsonb_old, lang);
# end;
# $body$;

# -----------------------------------------------------------------------------
# -- This is a test that calls the function "__arches_i18n_strip_jsonb_array"
# and should return w/o failing
# do $body$
# declare
# current_jsonb_old jsonb := '{
#     "options": [
#         {
#             "id": "cf18b6bd-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "tostada.test"},
#             "selected": false
#         },
#         {
#             "id": "aa18b6bd-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "burrito"},
#             "selected": false
#         },
#         {
#             "id": "bbbbbbbb-bb7b-4a51-aeb7-717aeb67e759",
#             "text": {"en": "lager"},
#             "selected": false
#         }
#     ]
# }';

# lang text := 'en';
# begin
# perform __arches_i18n_strip_jsonb_array('options.text',current_jsonb_old, lang);
# end;
# $body$;
