<script>
    import { onMount } from "svelte";

    import { FormGroup, Label, Input, Row, Col, Collapse, Fade } from "sveltestrap/src/index.js";
    import lodash from "lodash";

    import { storeMdjs } from "@/stores/mdjs.store";
    import { isOpenData, isGeoData } from "@/stores/app.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";
    import helpers from "@/libs/helpers";

    import InputField from "./elements/InputField.svelte";
    import MultiInputField from "./elements/MultiInputField.svelte";

    export let field;
    export let listLicenses;
    export let listRestrictionCode;
    export let listInspireRestrictionCode;
    export let listClassificationCode;

    let values = {
        dataLegalUseLimitations: [""],
        dataLegalUseConstraints: [""],
        dataLegalAccessConstraints: [""],
        dataLegalAccessInspireConstraints: [""],
    };

    const converter = new XmlConverter();

    $: isReady = $storeMdjs;
    $: $isOpenData = checkIsOpendata($storeMdjs);

    function checkIsOpendata(mdjs) {
        var keywords = converter.getValue(mdjs, "dataKeywordsList").map((kw) => {
            return kw.toLowerCase();
        });
        return keywords.includes("données ouvertes");
    }

    function onChangeLicense(fieldName, fieldValue) {
        if (fieldValue) {
            const list = lodash.cloneDeep(listLicenses);
            const license = list.find((l) => {
                return l.value == fieldValue;
            });
            values = {
                dataLegalUseLimitations: license.dataLegalUseLimitations,
                dataLegalUseConstraints: license.dataLegalUseConstraints,
                dataLegalAccessConstraints: license.dataLegalAccessConstraints,
                dataLegalAccessInspireConstraints: $isGeoData ? license.dataLegalAccessInspireConstraints : [""],
            };
            onSaveDataSecurityClassification("dataSecurityClassification", license.dataSecurityClassification);
            updateValues(fieldName, values);
        }
    }

    function onClickOpendata() {
        if (!$isOpenData) {
            // Define license values
            onChangeLicense("license", field.license.value);
            // Add "données ouvertes" to keywords
            var dataKeywords = converter.getValue($storeMdjs, "dataKeywords");
            var keyword = converter.setValue({}, "keyword", ["données ouvertes"]);
            converter.setValue(keyword, "keywordType", "theme");
            dataKeywords.push(keyword);
            converter.setValue($storeMdjs, "dataKeywords", dataKeywords);
        } else {
            // Define default values
            values = {
                // dataSecurityClassification: field.dataSecurityClassification.value,
                dataLegalUseLimitations: field.dataLegalUseLimitations.values,
                dataLegalUseConstraints: field.dataLegalUseConstraints.values,
                dataLegalAccessConstraints: field.dataLegalAccessConstraints.values,
                dataLegalAccessInspireConstraints: field.dataLegalAccessInspireConstraints.values,
            };
            // Remove "données ouvertes" keyword
            var dataKeywords = converter.getValue($storeMdjs, "dataKeywords");
            for (var kw = 0; kw < dataKeywords.length; kw++) {
                var keywords = converter.getValue(dataKeywords[kw], "keyword");
                if (keywords.includes("données ouvertes")) {
                    keywords.splice(keywords.indexOf("données ouvertes"), 1);
                    converter.setValue(dataKeywords[kw], "keyword", keywords);
                    converter.setValue($storeMdjs, "dataKeywords", dataKeywords);
                }
            }
        }
        onSaveDataSecurityClassification("dataSecurityClassification", field.dataSecurityClassification.value);
        updateValues(field.name, values);
    }

    function getValues(mdjs) {
        var dataResourceConstraints = converter.getValue(mdjs, "dataResourceConstraints");
        var legalUseLimitations = [];
        var legalUseConstraints = [];
        var legalAccessConstraints = [];
        var legalAccessInspireConstraints = [];
        for (var i = 0, n = dataResourceConstraints.length; i < n; i++) {
            var dataLegalUseLimitations = converter.getValue(dataResourceConstraints[i], "dataLegalUseLimitations");
            var dataLegalUseConstraints = converter.getValue(dataResourceConstraints[i], "dataLegalUseConstraints");
            var dataLegalAccessConstraints = converter.getValue(
                dataResourceConstraints[i],
                "dataLegalAccessConstraints"
            );
            var dataLegalAccessInspireConstraints = converter.getValue(
                dataResourceConstraints[i],
                "dataLegalAccessInspireConstraints"
            );
            if (dataLegalUseLimitations.length) {
                legalUseLimitations = dataLegalUseLimitations;
            }
            if (dataLegalUseConstraints.length) {
                legalUseConstraints = dataLegalUseConstraints;
            }
            if (dataLegalAccessConstraints.length) {
                legalAccessConstraints = dataLegalAccessConstraints.filter((value) => {
                    return value != "otherRestrictions";
                });
            }
            if (dataLegalAccessInspireConstraints.length) {
                legalAccessInspireConstraints = dataLegalAccessInspireConstraints;
            }
        }

        legalAccessInspireConstraints = $isGeoData
            ? helpers.cleanValues(legalAccessInspireConstraints, false, true)
            : [""];

        return {
            dataLegalUseLimitations: helpers.cleanValues(legalUseLimitations, false, true),
            dataLegalUseConstraints: helpers.cleanValues(legalUseConstraints, false, true),
            dataLegalAccessConstraints: helpers.cleanValues(legalAccessConstraints, false, true),
            dataLegalAccessInspireConstraints: legalAccessInspireConstraints,
        };
    }

    function onSaveDataSecurityClassification(fieldName, fieldValue) {
        var classification = converter.setValue({}, fieldName, [fieldValue]);

        // Get all resourceConstraints except securityConstraints
        var dataResourceConstraints = converter.getValue($storeMdjs, "dataResourceConstraints");
        var resourcesConstraints = [];
        for (var i = 0; i < dataResourceConstraints.length; i++) {
            const dataResourceConstraint = converter.getValue(dataResourceConstraints[i], "dataSecurityClassification");
            if (!dataResourceConstraint.length) {
                resourcesConstraints.push(dataResourceConstraints[i]);
            }
        }
        resourcesConstraints = resourcesConstraints.concat(classification);
        $storeMdjs = converter.setValue($storeMdjs, "dataResourceConstraints", resourcesConstraints);
        // value = getValue();
    }

    // TODO: fieldName non utilisé dans cette fonction => le supprimer partout
    function updateValues(fieldName, fieldValues) {
        const legals = [
            converter.setValue({}, "dataLegalUseLimitations", values.dataLegalUseLimitations),
            converter.setValue({}, "dataLegalUseConstraints", values.dataLegalUseConstraints),
            converter.setValue({}, "dataLegalAccessConstraints", values.dataLegalAccessConstraints),
            converter.setValue({}, "dataLegalAccessInspireConstraints", values.dataLegalAccessInspireConstraints),
        ];

        // Get all resourceConstraints except legalconstraints
        var dataResourceConstraints = converter.getValue($storeMdjs, "dataResourceConstraints");
        var resourcesConstraints = [];
        for (var i = 0; i < dataResourceConstraints.length; i++) {
            if (!converter.getValue(dataResourceConstraints[i], "dataLegalConstraints").length) {
                resourcesConstraints.push(dataResourceConstraints[i]);
            }
        }
        resourcesConstraints = resourcesConstraints.concat(legals);
        $storeMdjs = converter.setValue($storeMdjs, "dataResourceConstraints", resourcesConstraints);
    }

    $: values = getValues($storeMdjs);

    function getDataSecurityClassification(mdjs) {
        var dataResourceConstraints = converter.getValue(mdjs, "dataResourceConstraints");
        for (var i = 0; i < dataResourceConstraints.length; i++) {
            const dataResourceConstraint = converter.getValue(dataResourceConstraints[i], "dataSecurityClassification");
            if (dataResourceConstraint.length) {
                return dataResourceConstraint[0];
            }
        }
        return "";
    }

    $: valueDataSecurityClassification = getDataSecurityClassification($storeMdjs);

    onMount(() => {
        // $isOpenData = checkIsOpendata();
    });

    function onRemove(id, fieldName) {
        if (values[fieldName].length > 1) {
            values[fieldName].splice(id, 1);
        } else {
            values[fieldName][id] = "";
        }
        updateValues(fieldName, values);
    }

    function onSaveItems(fieldName, fieldValue, id) {
        values[fieldName][id] = fieldValue;
        updateValues(fieldName, values);
    }
</script>

{#if isReady}
    <Row>
        <Col md="6">
            <Label for="isOpenData">
                <strong class="mb-3">Données ouverte:</strong>
            </Label>
            <FormGroup inline check class="mb-4">
                <Input
                    type="switch"
                    id="is-open-data"
                    name="isOpenData"
                    label="oui"
                    inline
                    checked={$isOpenData == true}
                    value={true}
                    on:change={onClickOpendata}
                />
            </FormGroup>
        </Col>
        {#if $isOpenData}
            <Col md="6">
                <InputField
                    type={field.license.type}
                    value={field.license.value}
                    error={field.license.error}
                    field={field.license.name}
                    list={listLicenses}
                    onSave={onChangeLicense}
                />
            </Col>
        {/if}
    </Row>

    <Fade isOpen={!$isOpenData}>
        <Row class="d-none">
            <Col>
                <!-- DONE: dataSecurityClassification -->
                <InputField
                    label={field.dataSecurityClassification.label}
                    type={field.dataSecurityClassification.type}
                    value={valueDataSecurityClassification}
                    list={listClassificationCode}
                    help={field.dataSecurityClassification.help}
                    error={field.dataSecurityClassification.error}
                    field={field.dataSecurityClassification.name}
                    strong={true}
                    onSave={onSaveDataSecurityClassification}
                />
                <!-- <DataSecurityClassification field={field.dataSecurityClassification} list={listClassificationCode} /> -->
            </Col>
        </Row>
        <Row class={$isGeoData ? "" : "d-none"}>
            <Col>
                <!-- DONE: dataLegalAccessInspireConstraints -->
                <MultiInputField
                    field={field.dataLegalAccessInspireConstraints}
                    values={values.dataLegalAccessInspireConstraints}
                    list={listInspireRestrictionCode}
                    onSave={onSaveItems}
                    {onRemove}
                    strong={true}
                />
            </Col>
        </Row>
        <Row>
            <Col>
                <!-- DONE: dataLegalAccessConstraints -->
                <MultiInputField
                    field={field.dataLegalAccessConstraints}
                    values={values.dataLegalAccessConstraints}
                    list={listRestrictionCode}
                    onSave={onSaveItems}
                    {onRemove}
                    strong={true}
                />
            </Col>
        </Row>
        <Row>
            <Col>
                <!-- DONE: dataLegalUseConstraints -->
                <MultiInputField
                    field={field.dataLegalUseConstraints}
                    values={values.dataLegalUseConstraints}
                    list={listRestrictionCode}
                    onSave={onSaveItems}
                    {onRemove}
                    strong={true}
                />
            </Col>
        </Row>
    </Fade>

    <Row>
        <Col>
            <!-- DONE: dataLegalUseLimitations -->
            <MultiInputField
                field={field.dataLegalUseLimitations}
                values={values.dataLegalUseLimitations}
                onSave={onSaveItems}
                {onRemove}
                strong={true}
            />
        </Col>
    </Row>
{/if}

<style>
</style>
