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

    import { Row, Col, Button, Icon, FormText, Styles } from "sveltestrap";

    import lodash from "lodash";

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

    import Contact from "./Contact.svelte";

    export let field;
    export let roles;
    export let type;

    let values = [];
    let displayHelp = false;
    let error = {
        required: true,
        message: false,
    };

    $: isReady = $storeMdjs;

    $: {
        const contacts = getValues($storeMdjs, false);
        let isValid = [];
        let valid = false;
        for (let i = 0, n = contacts.length; i < n; i++) {
            valid =
                isDefined(converter.getValue(contacts[i], "organisationName")) &&
                isDefined(converter.getValue(contacts[i], "emails")) &&
                isDefined(converter.getValue(contacts[i], "role"))
                    ? true
                    : false;
            isValid.push(valid);
        }
        error.required = field.error.required ? isValid.every((value) => value == false) : false;
    }

    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 isContact(contact) {
        return (
            isDefined(converter.getValue(contact, "individualName")) ||
            isDefined(converter.getValue(contact, "positionName")) ||
            isDefined(converter.getValue(contact, "organisationName")) ||
            isDefined(converter.getValue(contact, "phoneVoices")) ||
            isDefined(converter.getValue(contact, "emails")) ||
            isDefined(converter.getValue(contact, "deliveryPoints")) ||
            isDefined(converter.getValue(contact, "postalCode")) ||
            isDefined(converter.getValue(contact, "city")) ||
            isDefined(converter.getValue(contact, "logoUrl")) ||
            isDefined(converter.getValue(contact, "logoDescription")) ||
            isDefined(converter.getValue(contact, "role"))
        );
    }

    function getValues(mdjs, addEmpty) {
        var contacts = converter.getValue(mdjs, field.name) || [{}];
        var result = [];
        for (var i = 0, n = contacts.length; i < n; i++) {
            if (isContact(contacts[i])) {
                result.push(contacts[i]);
            }
        }
        if (addEmpty) {
            result.push({});
        }
        return result;
    }

    $: values = getValues($storeMdjs, true);

    function onCloneItem(id) {
        onSaveItem(values.length, lodash.cloneDeep(values[id]));
    }

    function duplicateContact(contactsFieldName, contact) {
        var contacts = converter.getValue($storeMdjs, contactsFieldName);
        contacts[contacts.length - 1] = lodash.cloneDeep(contact);
        contacts.push({});
        $storeMdjs = converter.setValue($storeMdjs, contactsFieldName, contacts);
    }

    function onDuplicateItem(id) {
        const contactsType = type == "mdContacts" ? "dataPointOfContacts" : "mdContacts";
        duplicateContact(contactsType, values[id]);
    }

    function onAddUserContact(id) {
        let cnt = converter.setValue({}, field.name);
        converter.setValue(cnt, "individualName", [[$user.firstname, $user.lastname].join(' ')]);
        converter.setValue(cnt, "organisationName", [$user.orgname]);
        converter.setValue(cnt, "phoneVoices", [$user.tel]);
        converter.setValue(cnt, "emails", [$user.email]);
        converter.setValue(cnt, "role", ["pointOfContact"]);
        onSaveItem(id, cnt);
    }

    onMount(() => {});

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

    function onSaveItem(id, value) {
        values[id] = value;
        $storeMdjs = converter.setValue($storeMdjs, field.name, values);
        // console.log(4444, values, value, field.name);
    }
</script>

<!-- {JSON.stringify(values)} -->

<Row>
    <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}
        <!-- If display help -->
        {#if displayHelp}
            <FormText color="muted" class="d-block">
                {@html helpers.nl2br(field.help)}
            </FormText>
        {/if}
    </Col>
</Row>

<hr />

<Row class="my-2">
    <Col>
        {#each values as value, id}
            <Contact
                field={field.children}
                {value}
                {id}
                {onRemoveItem}
                {onSaveItem}
                {onCloneItem}
                {onDuplicateItem}
                {onAddUserContact}
                {roles}
                {type}
                {error}
            />
            <hr />
        {/each}
    </Col>
</Row>
