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

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

    import lodash from "lodash";

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

    import DataGeographicExtent from "./DataGeographicExtent.svelte";

    export let field;

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

    // let extentView = "basic";
    function onChangeMode(e, mode) {
        e.preventDefault();
        e.stopPropagation();
        // extentView = extentView == "advanced" ? "basic" : "advanced";
        advancedMode = mode == "advanced" ? true : false;
    }

    $: isReady = $storeMdjs;
    $: {
        const geographicExtents = getValues($storeMdjs, "geographic");
        let isValid = [];
        let valid = false;
        for (let i = 0, n = geographicExtents.length; i < n; i++) {
            if ($isGeoData) {
                valid =
                    isDefined(converter.getValue(geographicExtents[i], "extentName")) &&
                    isDefined(converter.getValue(geographicExtents[i], "geographicExtentWestBound")) &&
                    isDefined(converter.getValue(geographicExtents[i], "geographicExtentEastBound")) &&
                    isDefined(converter.getValue(geographicExtents[i], "geographicExtentSouthBound")) &&
                    isDefined(converter.getValue(geographicExtents[i], "geographicExtentNorthBound"))
                        ? true
                        : false;
            } else {
                valid = isDefined(converter.getValue(geographicExtents[i], "extentName")) ? true : false;
            }
            isValid.push(valid);
        }
        error.required = field.error.required ? isValid.every((value) => value == false) : false;
    }

    const converter = new XmlConverter();

    function isDefined(array) {
        return array.filter((item) => item).length;
    }

    function isTemporalExtent(dataExtent) {
        return (
            isDefined(converter.getValue(dataExtent, "temporalExtentBegin")) ||
            isDefined(converter.getValue(dataExtent, "temporalExtentEnd"))
        );
    }

    function isGeographicExtent(dataExtent) {
        return (
            isDefined(converter.getValue(dataExtent, "geographicExtentWestBound")) ||
            isDefined(converter.getValue(dataExtent, "geographicExtentEastBound")) ||
            isDefined(converter.getValue(dataExtent, "geographicExtentSouthBound")) ||
            isDefined(converter.getValue(dataExtent, "geographicExtentNorthBound"))
        );
    }

    function getExtents(dataExtents, type) {
        var geographicExtents = [];
        var temporalExtents = [];
        for (var i = 0; i < dataExtents.length; i++) {
            if (isGeographicExtent(dataExtents[i])) {
                geographicExtents.push(dataExtents[i]);
            } else if (isTemporalExtent(dataExtents[i])) {
                temporalExtents.push(dataExtents[i]);
            }
        }

        if (type == "temporal") {
            temporalExtents.push({});
            return temporalExtents;
        } else {
            geographicExtents.push({});
            return geographicExtents;
        }
    }

    function getValues(mdjs, type) {
        var dataExtents = mdjs ? converter.getValue(mdjs, field.name) : [{}];
        return getExtents(dataExtents, type);
    }

    $: values = getValues($storeMdjs, "geographic");

    onMount(() => {
        helpers.getFile("config/views/formData/extents.json").then((response) => {
            extents = response.data;
        });
    });

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

    function onSaveItem(id, geographicextent) {
        if (isGeographicExtent(geographicextent) || Object.keys(geographicextent).length === 0) {
            values[id] = geographicextent;
            values = getExtents(values, "geographic");

            // Keep only no geo dataExtents and add new geographicextents
            var dataExtents = converter.getValue($storeMdjs, field.name);
            var temporalextents = getExtents(dataExtents, "temporal");
            var newDataExtents = temporalextents.concat(values);

            $storeMdjs = converter.setValue($storeMdjs, field.name, newDataExtents);
        }
    }
</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}
        <!-- Basic/Advanced view button -->
        <ButtonGroup size="sm" class="float-end p-0">
            <Button
                outline={advancedMode}
                color={advancedMode ? "secondary" : "primary"}
                class="py-0 px-1"
                on:click={(e) => onChangeMode(e, 'basic') }
            >
                <small>Vue simple</small>
            </Button>
            <Button
                outline={!advancedMode}
                color={advancedMode ? "primary" : "secondary"}
                class="py-0 px-1"
                on:click={(e) => onChangeMode(e, 'advanced')}
            >
                <small>Vue avancée</small>
            </Button>
        </ButtonGroup>
        <!-- If display help -->
        {#if displayHelp}
            <FormText color="muted" class="d-block">
                {@html helpers.nl2br(field.help)}
            </FormText>
        {/if}
    </Col>
</Row>

<Row>
    {#if advancedMode}
        <Col md="3">
            {field.children.extentName.label}
        </Col>
        <Col md="2">
            {field.children.geographicExtentWestBound.label}
        </Col>
        <Col md="2">
            {field.children.geographicExtentEastBound.label}
        </Col>
        <Col md="2">
            {field.children.geographicExtentSouthBound.label}
        </Col>
        <Col md="2">
            {field.children.geographicExtentNorthBound.label}
        </Col>
    {:else}
        <Col md="6">
            {field.children.extentName.label}
        </Col>
    {/if}
    <Col md="1" />
</Row>

<Row class="my-2">
    <Col>
        {#each values as value, id}
            <DataGeographicExtent field={field.children} {value} {id} {extents} {onRemoveItem} {onSaveItem} {error} {advancedMode} />
        {/each}
    </Col>
</Row>
<Row class="justify-content-md-end">
    <Col>
        {#if $validateForm && error.required && field.error.message}
            <small class="text-danger">{field.error.message}</small>
        {/if}
    </Col>
</Row>
