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

    import { Button, Col, Row, Input, Fade, FormGroup, Label, FormText, Icon, ButtonGroup } from "sveltestrap";

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

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

    export let field;
    export let keywordTypes = [];
    export let advancedMode = false;

    let kw = { keywordsList: [{}], ikeywordsList: [{}] };
    let basicKeywords = [""];

    const converter = new XmlConverter();

    // TODO:  Put in helpers (use isEmptyArray)
    function isDefined(array) {
        return array.filter((item) => item).length;
    }

    // TODO: etudier possibilité d'utiliser une function générique dans helpers
    function isKeyword(keyword) {
        return isDefined(converter.getValue(keyword, "keyword"));
    }

    function getValues(mdjs) {
        var keywords = mdjs ? converter.getValue(mdjs, field.name) : [{}];
        var keywordsList = [];
        var ikeywordsList = [];
        for (var k = 0, n = keywords.length; k < n; k++) {
            var thesaurusName = converter.getValue(keywords[k], "thesaurusName")[0] || "";
            if (isKeyword(keywords[k])) {
                if (thesaurusName && thesaurusName.toLowerCase().includes("inspire")) {
                    ikeywordsList.push(keywords[k]);
                } else {
                    keywordsList.push(keywords[k]);
                }
            }
        }
        keywordsList.push({});
        return { keywordsList: keywordsList, ikeywordsList: ikeywordsList };
    }

    // console.log(111, typeof Array.prototype.flat());

    $: isReady = $storeMdjs;
    $: {
        kw = getValues($storeMdjs);
        let values = converter.getValue(kw.keywordsList[0], "keyword") || [""];
        // basicKeywords = values
        //     .flat(1)
        //     .map((v) => v.trim())
        //     .join(", ");
        basicKeywords = values
            .reduce((acc, val) => acc.concat(val), [])
            .map((v) => v.trim())
            .join(", ");
    }

    onMount(() => {
        keywordView = kw.keywordsList.length > 2 ? "advanced" : "basic";
    });

    let keywordView = "basic";
    function onChangeKeywordView(e) {
        e.preventDefault();
        e.stopPropagation();
        keywordView = keywordView == "advanced" ? "basic" : "advanced";
    }

    let displayHelp = false;

    function onRemoveItem(id) {
        if (kw.keywordsList.length > 1) {
            kw.keywordsList.splice(id, 1);
        } else {
            kw.keywordsList[id] = {};
        }
        $storeMdjs = converter.setValue($storeMdjs, field.name, kw.keywordsList.concat(kw.ikeywordsList));
    }

    function onSaveBasicItem(fieldName, fieldValue, id) {
        // TODO: mettre la liste des séparateurs de mots-clés dans le fichier de config
        const separators = ["\n", ",", ";"];
        // var fieldValue = fieldValue
        //     .split(new RegExp(separators.join("|"), "g"))
        //     .flat(1)
        //     .map((v) => v.trim());

        var fieldValue = fieldValue
            .split(new RegExp(separators.join("|"), "g"))
            .reduce((acc, val) => acc.concat(val), [])
            .map((v) => v.trim());
        var keyword = converter.setValue({}, "keyword", fieldValue);
        keyword = converter.setValue(keyword, "keywordType", "theme");
        kw.keywordsList[0] = keyword;
        $storeMdjs = converter.setValue($storeMdjs, field.name, kw.keywordsList.concat(kw.ikeywordsList));
    }

    function onSaveAdvancedItem(fieldName, fieldValue, id) {
        // Check mandatory field "keywordType"
        var keywordType = converter.getValue(fieldValue, "keywordType")[0] || false;
        if (!keywordType) {
            fieldValue = converter.setValue(fieldValue, "keywordType", "theme");
        }
        kw.keywordsList[id] = fieldValue;
        $storeMdjs = converter.setValue($storeMdjs, field.name, kw.keywordsList.concat(kw.ikeywordsList));
    }
</script>

{#if isReady}
    <Row class="my-2">
        <Col>
            <strong>{field.label}</strong>
            <!-- If help -->
            {#if field.help}
                <span
                    class="link"
                    on:click={() => {
                        displayHelp = !displayHelp;
                    }}
                >
                    <Icon name="info-circle-fill" class="ms-1 mb-1" />
                </span>
            {/if}
            <!-- Basic/Advanced view button -->
            {#if advancedMode}
                <ButtonGroup size="sm" class="float-end p-0">
                    <Button
                        outline={keywordView == "advanced"}
                        color={keywordView == "advanced" ? "secondary" : "primary"}
                        class="py-0 px-1"
                        on:click={onChangeKeywordView}
                    >
                        <small>Vue simple</small>
                    </Button>
                    <Button
                        outline={keywordView != "advanced"}
                        color={keywordView == "advanced" ? "primary" : "secondary"}
                        class="py-0 px-1"
                        on:click={onChangeKeywordView}
                    >
                        <small>Vue avancée</small>
                    </Button>
                </ButtonGroup>
            {/if}
            <!-- If display help -->
            {#if displayHelp}
                <FormText color="muted" class="d-block">
                    {@html helpers.nl2br(field.help)}
                </FormText>
            {/if}
        </Col>
    </Row>

    <Row>
        <Col>
            <Fade isOpen={keywordView == "basic"}>
                <!-- <InputField id={field.id} type="textarea" value={fieldValue} on:blur={onBlur} /> -->
                <InputField
                    label=""
                    type={field.type}
                    value={basicKeywords}
                    help={field.help}
                    error={field.error}
                    field={field.name}
                    onSave={onSaveBasicItem}
                    rows={3}
                />
            </Fade>
            <Fade isOpen={keywordView == "advanced"}>
                <Row class="my-1">
                    <Col>
                        <!-- {JSON.stringify(field)} -->
                        {#each kw.keywordsList as keyword, id}
                            <DataKeyword
                                field={field.children}
                                value={keyword}
                                {id}
                                {keywordTypes}
                                {onRemoveItem}
                                onSaveItem={onSaveAdvancedItem}
                            />
                        {/each}
                    </Col>
                </Row>
            </Fade>
            <!-- If error -->
            {#if field.error.validation == "required"}
                <div class="invalid-feedback">{field.error.text}</div>
            {/if}
        </Col>
    </Row>
{/if}

<style>
</style>
