<script>
    import { onMount } from "svelte";
    import { querystring, push, location, link } from "svelte-spa-router";
    import {
        Button,
        Col,
        Row,
        Form,
        Container,
        Input,
        ButtonToolbar,
        NavItem,
        NavLink,
        Fade,
        FormGroup,
        Label,
        Card,
        CardBody,
        ButtonGroup,
        ButtonDropdown,
        Dropdown,
        DropdownItem,
        DropdownMenu,
        DropdownToggle,
        Tooltip,
        Icon,
        Collapse,
        Toast,
        ToastBody,
        ToastHeader,
        Nav,
        Navbar,
        NavbarBrand,
    } from "sveltestrap";

    import lodash from "lodash";

    import MdFileIdentifier from "@/components/md-form/MdFileIdentifier.svelte";
    import MdCharacterSet from "@/components/md-form/MdCharacterSet.svelte";
    import MdDateStamp from "@/components/md-form/MdDateStamp.svelte";
    import MdHierarchyLevel from "@/components/md-form/MdHierarchyLevel.svelte";
    import MdLanguage from "@/components/md-form/MdLanguage.svelte";
    import MdParentIdentifier from "@/components/md-form/MdParentIdentifier.svelte";
    import MdStandardName from "@/components/md-form/MdStandardName.svelte";
    import MdStandardVersion from "@/components/md-form/MdStandardVersion.svelte";
    import DataTitle from "@/components/md-form/DataTitle.svelte";
    import DataAbstract from "@/components/md-form/DataAbstract.svelte";
    import DataKeywords from "@/components/md-form/DataKeywords.svelte";
    import DataDates from "@/components/md-form/DataDates.svelte";
    import DataBrowseGraphics from "@/components/md-form/DataBrowseGraphics.svelte";
    import DataIdentifiers from "@/components/md-form/DataIdentifiers.svelte";
    import DataGeographicExtents from "@/components/md-form/DataGeographicExtents.svelte";
    import DataTemporalExtents from "@/components/md-form/DataTemporalExtents.svelte";
    import DataInspireKeywords from "@/components/md-form/DataInspireKeywords.svelte";
    import DataThemeKeywords from "@/components/md-form/DataThemeKeywords.svelte";
    import DataMaintenanceFrequency from "@/components/md-form/DataMaintenanceFrequency.svelte";
    import DataLanguages from "@/components/md-form/DataLanguages.svelte";
    import DataReferenceSystems from "@/components/md-form/DataReferenceSystems.svelte";
    import DataLiStatement from "@/components/md-form/DataLiStatement.svelte";
    import DataCharacterSet from "@/components/md-form/DataCharacterSet.svelte";
    import DataUseLimitations from "@/components/md-form/DataUseLimitations.svelte";
    import DataDistributionFormats from "@/components/md-form/DataDistributionFormats.svelte";
    import DataLinkages from "@/components/md-form/DataLinkages.svelte";
    import DataSpatialResolution from "@/components/md-form/DataSpatialResolution.svelte";
    import DataSpatialRepresentationType from "@/components/md-form/DataSpatialRepresentationType.svelte";
    import Contacts from "@/components/md-form/Contacts.svelte";
    import DataTopicCategories from "@/components/md-form/DataTopicCategories.svelte";
    import DataLegalConstraints from "@/components/md-form/DataLegalConstraints.svelte";

    import { XmlConverter } from "@/libs/xml-converter/xml-converter";
    import helpers from "@/libs/helpers";
    import download from "@/libs/download";

    import {
        storeConfig,
        storeLang,
        storeLocales,
        storeLocalesViews,
        storeModel,
        storeFile,
    } from "@/stores/config.store";
    import { isGeoData, validateForm, user, isModel } from "@/stores/app.store";
    import { storeMdjs, storeThemeKeywords, storeInspireKeywords } from "@/stores/mdjs.store";
    import { storeFiles, storeUrlFiles, storeDeletedFiles, storeNewFiles } from "@/stores/files.store";

    const converter = new XmlConverter();

    let loading = 0;
    let model = {};
    let advancedView = false;
    let viewMenu = true;
    let messages = [];

    const view = "formData";
    $: mdUrl = helpers.getUrlParameter($querystring, "xml", false);
    $: storeFile.setFile(mdUrl, "url", "xml");
    $: localesView = $storeLocalesViews[view];
    $: isReady = localesView;
    $: {
        $isGeoData = converter.getValue($storeMdjs, "dataSpatialRepresentationType")[0] ? true : false;
    }
    $: dataTitle = $storeMdjs ? converter.getValue($storeMdjs, "dataTitle")[0] : "";
    $: mdFileIdentifier = $storeMdjs ? converter.getValue($storeMdjs, "mdFileIdentifier")[0] : "";

    onMount(() => {
        const file = $storeConfig.views[view].locales[$storeLang];
        storeLocalesViews.setLocalesView(view, file);

        if (!$storeFile) {
            model = getModel($storeConfig, view);
            storeModel.setModel(model);
        }
    });

    function onChangeGeoData() {
        if ($isGeoData) {
            converter.setValue($storeMdjs, "dataSpatialRepresentationType", null);
        } else {
            converter.setValue($storeMdjs, "dataSpatialRepresentationType", ["vector"]);
        }
        $isGeoData = !$isGeoData;
    }

    function getModel(config, formName) {
        const form = config.forms.find((form) => form.name == formName);
        return config.models.find((m) => m.code == form.model);
    }

    let activeTab;
    $: {
        if (localesView) {
            activeTab = "tab" + localesView.defaultActiveTab;
        }
    }

    $: href = {
        load: $querystring ? "/load?" + $querystring : "/load",
        list: $querystring ? "/list?" + $querystring : "/list",
        view: $querystring ? "/view?" + $querystring : "/view",
        home: $querystring ? "/?" + $querystring : "/",
        reload: $querystring ? "/" + view + "?" + $querystring : "/" + view,
    };

    function changeTab(key) {
        activeTab = key;
    }

    function onChangeAdvancedView() {
        advancedView = !advancedView;
    }

    function onDownload() {
        const file = download.generateXml($storeMdjs, $isGeoData, false, false, localesView);
        download.downloadXml(unescape(encodeURIComponent(file.xml)), file.uuid + ".xml");
        $storeMdjs = file.mdjs;
    }
    function onDownloadModel() {
        const file = download.generateXml($storeMdjs, $isGeoData, false, false, localesView, true);
        const now = lodash.now();
        const filename = lodash.uniqueId(now + "-") + ".xml";
        download.downloadXml(unescape(encodeURIComponent(file.xml)), filename);
        $storeMdjs = file.mdjs;
    }

    function onNewFile() {
        model = $storeConfig.models.find((m) => m.code == "empty");
        storeModel.setModel(model);
        $storeThemeKeywords = [{}];
        $storeInspireKeywords = [{}];
    }

    function onDuplicateFile() {
        $storeMdjs = converter.setValue($storeMdjs, "mdFileIdentifier", [""]);
    }

    async function saveFiles(file, org, api) {
        loading = 1;
        messages = [];

        const directory = api.url_base + org + "/";

        // 1. if oldFileId && uuid != oldFileId => copier le répertoire oldFileId en uuid
        if (file.oldFileId && file.uuid != file.oldFileId) {
            // const oldFileId = lodash.cloneDeep(fileId);
            const src_directory = org + "/" + file.oldFileId;
            const dst_directory = org + "/" + file.uuid;
            const copyDir = await fetch(
                api.directories + "&copy=1&directories=" + encodeURIComponent([src_directory, dst_directory].join(";")),
                { method: "PUT" }
            );
            // console.log(11, "copyDir", await copyDir.json());

            const old_file = dst_directory + "/" + file.oldFileId + ".xml";
            const deletedXml = await fetch(api.files + "&files=" + encodeURIComponent(old_file), {
                method: "DELETE",
            });
            // console.log(12, "deleteXml", await deletedXml.json());
        }

        // 2. enregistrer le fichier uuid.xml
        const data = [
            {
                file: org + "/" + file.uuid + "/" + file.uuid + ".xml",
                content: file.xml,
            },
        ];
        const options = {
            method: "POST",
            body: JSON.stringify(data),
            headers: {
                "Content-Type": "application/json",
            },
        };
        const savedXml = await fetch($storeConfig.api.files, options);
        const savedXmlResponse = await savedXml.json();
        let savedXmlMessage = {
            open: true,
            autohide: false,
            icon: "danger",
            title: "Erreur",
            content:
                "La fiche n'a pas pu être sauvegardée. Merci de vérifier les données saisies. Si le problème persiste vous pouvez contacter un administrateur de la plateforme (contact@datagrandest.fr).",
        };
        if (savedXmlResponse.success) {
            savedXmlMessage.icon = "success";
            savedXmlMessage.autohide = true;
            savedXmlMessage.title = "Information";
            savedXmlMessage.content = "La fiche a bien été enregistrée sur la plateforme.";
        }
        messages.push(savedXmlMessage);
        // console.log(13, "saveXML", savedXmlResponse, savedXmlMessage);

        // 3. add new files + get server files and remove files with URL not in XML

        // Get allFiles from $storeUrlFiles, remove empty values, replace file:/// by base_url and keep only url start with base_url
        var allFiles = helpers.cleanValues(Object.values($storeUrlFiles));
        // console.log(100, $storeUrlFiles, allFiles, directory);
        allFiles = allFiles
            .map((url) => {
                return url.replace("file:///", directory + file.uuid + "/");
            })
            .filter((url) => {
                return url.startsWith(directory + file.uuid + "/") == true;
            });
        allFiles.push(directory + file.uuid + "/" + file.uuid + ".xml");

        // Save $storeNewFiles to the server
        const newFiles = Object.values($storeNewFiles);
        // if (newFiles.length) {
        //     const formData = new FormData();
        //     for (let i = 0, n = newFiles.length; i < n; i++) {
        //         formData.append("files[]", newFiles[i]);
        //     }

        //     const savedFiles = await fetch(
        //         $storeConfig.api.files + "&upload=1&directory=" + org + "/" + file.uuid + "/",
        //         {
        //             method: "POST",
        //             body: formData,
        //         }
        //     );
        //     console.log(14, await savedFiles.json());
        // }
        if (newFiles.length) {
            for (let i = 0, n = newFiles.length; i < n; i++) {
                const formData = new FormData();
                formData.append("files[]", newFiles[i]);
                const savedFiles = await fetch(
                    $storeConfig.api.files + "&upload=1&directory=" + org + "/" + file.uuid + "/",
                    {
                        method: "POST",
                        body: formData,
                    }
                );
                const savedFilesResponse = await savedFiles.json();
                let savedFilesMessage = {
                    open: true,
                    autohide: false,
                    icon: "danger",
                    title: "Erreur",
                    content:
                        "Le fichier " +
                        newFiles[i].name +
                        " n'a pas pu être sauvegardée. Merci de vérifier sa taille et son format. Si le problème persiste vous pouvez contacter un administrateur de la plateforme (contact@datagrandest.fr).",
                };
                if (savedFilesResponse.success) {
                    savedFilesMessage.icon = "success";
                    savedFilesMessage.autohide = true;
                    savedFilesMessage.title = "Information";
                    savedFilesMessage.content =
                        "Le fichier " + newFiles[i].name + " a bien été enregistrée sur la plateforme.";
                }
                messages.push(savedFilesMessage);
                // c:onsole.log(14, "add new file", i, newFiles[i], savedFilesResponse, savedFilesMessage);
            }
        }

        // Clean directory: remove files without URL in XML
        // Get directory files
        const dirFiles = await fetch($storeConfig.api.files + "&directory=" + org + "/" + file.uuid + "/");
        const dirFilesJson = await dirFiles.json();
        // console.log(dirFilesJson);

        const serverFiles = dirFilesJson.files;
        var deleteFiles = [];
        if (serverFiles.length) {
            // Compare directory files list with allFiles and populate deleteFiles
            for (let i = 0, n = serverFiles.length; i < n; i++) {
                if (!allFiles.includes(serverFiles[i].url)) {
                    deleteFiles.push(serverFiles[i].file);
                }
            }
        }
        // console.log(111, allFiles, serverFiles, deleteFiles);
        // Remove files of deleteFiles
        if (deleteFiles.length) {
            for (let i = 0, n = deleteFiles.length; i < n; i++) {
                const deletedFiles = await fetch(
                    $storeConfig.api.files + "&files=" + encodeURIComponent(deleteFiles[i]),
                    {
                        method: "DELETE",
                        headers: {
                            "Content-Type": "application/json",
                        },
                    }
                );
                const deletedFilesResponse = await deletedFiles.json();
                const deletedFile = deleteFiles[i].replace(/^.*[\\\/]/, "");
                let deletedFilesMessage = {
                    open: true,
                    autohide: false,
                    icon: "danger",
                    title: "Erreur",
                    content:
                        "Le fichier " +
                        deletedFile +
                        "n'a pas pu être supprimé. Si le problème persiste vous pouvez contacter un administrateur de la plateforme (contact@datagrandest.fr).",
                };
                if (deletedFilesResponse.success) {
                    deletedFilesMessage.icon = "success";
                    deletedFilesMessage.autohide = true;
                    deletedFilesMessage.title = "Information";
                    deletedFilesMessage.content =
                        "Le fichier " + deletedFile + " a bien été supprimé de la plateforme.";
                }
                messages.push(deletedFilesMessage);
                // console.log(15, "delete file", i, deletedFilesResponse, deletedFilesMessage);
            }
        }

        messages = messages;
        // console.log(16, messages);
        loading = 0;

        // Empty files stores
        $storeFiles = [];
        // $storeUrlFiles = [];
        $storeDeletedFiles = [];
        $storeNewFiles = [];
    }

    function onSave(org) {
        // TODO: mettre une partie du code dans des fonctions
        org = org || $user.orgs[0];
        // const directory = $storeConfig.api.url_base + org.directory + "/";
        const dataTitle = converter.getValue($storeMdjs, "dataTitle")[0] || false;
        const dataAbstract = converter.getValue($storeMdjs, "dataAbstract")[0] || false;
        // const dataIdentifiers = converter.getValue($storeMdjs, "dataIdentifiersCodes").filter((el) => el);
        // const dataId = dataIdentifiers[0] || false;
        if (!dataTitle || !dataAbstract) {
            alert(
                [
                    "Le titre, le résumé et l'identifiant de la donnée sont des éléments obligatoires afin de pouvoir enregistrer la fiche.",
                    "Merci de les compléter et de vous référer à l'aide en ligne au besoin.",
                ].join("\n")
            );
        } else {
            const file = download.generateXml($storeMdjs, $isGeoData, $storeConfig.api, org.directory, localesView);
            $storeMdjs = file.mdjs;
            // console.log(125, file.uuid);
            saveFiles(file, org.directory, $storeConfig.api);
        }
    }

    function onChangeSidebarView(e) {
        e.preventDefault();
        e.stopPropagation();
        viewMenu = !viewMenu;
        // console.log("change isModel:", $isModel);
    }

    function goTo(href) {
        push(href);
    }
</script>

{#if isReady}
    <Container>
        <Navbar color="white" light sticky="top" class="border-bottom m-0 p-0">
            <NavbarBrand href="#/">
                <Icon name="journal-richtext" class="" style="font-size: 2rem;" />
                mdEdit 3
            </NavbarBrand>

            <Nav class="" navbar>
                <ButtonToolbar class="float-end gap-1">
                    <Button outline color="dark" on:click={(e) => goTo(href.home)}>Accueil</Button>

                    <ButtonDropdown>
                        <DropdownToggle outline color="dark" caret>Fiche</DropdownToggle>
                        <DropdownMenu>
                            <DropdownItem on:click={(e) => goTo(href.view)}>Visionner</DropdownItem>
                            <DropdownItem on:click={onDownload}>Télécharger</DropdownItem>
                            {#if $user.editor}
                                {#if $user.orgs.length == 1}
                                    <DropdownItem
                                        outline
                                        color="dark"
                                        on:click={() => {
                                            onSave();
                                        }}>Enregistrer</DropdownItem
                                    >
                                {:else}
                                    <DropdownItem divider />
                                    {#each $user.orgs as org}
                                        <DropdownItem
                                            on:click={() => {
                                                onSave(org);
                                            }}>Enregistrer dans {org.name}</DropdownItem
                                        >
                                    {/each}
                                    <DropdownItem divider />
                                {/if}
                            {/if}
                            <DropdownItem outline color="dark" on:click={onDuplicateFile}>Dupliquer</DropdownItem>
                        </DropdownMenu>
                    </ButtonDropdown>

                    <ButtonDropdown>
                        <DropdownToggle id="button-download" outline color="dark" caret>Modèle</DropdownToggle>
                        <DropdownMenu>
                            <DropdownItem on:click={onDownloadModel}>Télécharger</DropdownItem>
                        </DropdownMenu>
                    </ButtonDropdown>

                    <Button outline color="dark" on:click={onNewFile}>Nouveau</Button>
                </ButtonToolbar>
            </Nav>
        </Navbar>
    </Container>

    <Container class="my-3">
        <div hidden={!loading}>
            <div class="d-flex justify-content-center">
                <div class="m-5 text-center">
                    <div class="spinner-grow" role="status" />
                    <div><small class="text-muted">Sauvegarde en cours...</small></div>
                </div>
            </div>
        </div>
        <div hidden={loading}>
            <Row>
                <div class="col-12 col-xxl-3 col-xl-4 col-lg-4 col-md-4 pl-2 mb-3" class:hidden={viewMenu === false}>
                    <Card>
                        <CardBody>
                            <Row>
                                <Col class="text-center mb-3">
                                    <!-- Basic/Advanced view button -->
                                    <ButtonGroup size="sm">
                                        <Button
                                            outline={advancedView}
                                            color={advancedView ? "secondary" : "primary"}
                                            on:click={onChangeAdvancedView}
                                        >
                                            Vue simple
                                        </Button>
                                        <Button
                                            outline={!advancedView}
                                            color={advancedView ? "primary" : "secondary"}
                                            on:click={onChangeAdvancedView}
                                        >
                                            Vue complète
                                        </Button>
                                    </ButtonGroup>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <Nav vertical pills>
                                        {#each localesView.tabs as tab}
                                            {#if !tab.advanced || (tab.advanced && advancedView)}
                                                {#if tab.disabled}
                                                    <NavItem>
                                                        <NavLink
                                                            id={"tab" + tab.id}
                                                            disabled
                                                            class="text-dark pl-0"
                                                            title="tab.description"
                                                        >
                                                            <strong>{tab.title}</strong>
                                                        </NavLink>
                                                    </NavItem>
                                                {:else}
                                                    <NavItem>
                                                        <NavLink
                                                            active={activeTab == "tab" + tab.id}
                                                            id={"tab" + tab.id}
                                                            data-toggle={"tab" + tab.id}
                                                            role="tab"
                                                            aria-controls={"tab" + tab.id}
                                                            aria-selected="true"
                                                            on:click={() => changeTab("tab" + tab.id)}
                                                        >
                                                            {tab.title}
                                                        </NavLink>
                                                    </NavItem>
                                                {/if}
                                            {/if}
                                        {/each}
                                        <NavItem>
                                            <hr />
                                        </NavItem>
                                        <NavItem>
                                            <Button
                                                on:click={(e) => goTo(href.load)}
                                                block
                                                outline
                                                color="dark"
                                                class="my-2"
                                            >
                                                Charger une fiche ou un modèle
                                            </Button>
                                        </NavItem>
                                        {#if $user.editor}
                                            <NavItem>
                                                <Button
                                                    on:click={(e) => goTo(href.list)}
                                                    block
                                                    outline
                                                    color="dark"
                                                    class="my-2"
                                                >
                                                    Lister mes fiches de métadonnées
                                                </Button>
                                            </NavItem>
                                        {/if}
                                    </Nav>
                                </Col>
                            </Row>
                            <Row>
                                <Col class="text-center mt-2">
                                    <small class="text-muted" hidden={!mdFileIdentifier}>
                                        <em>File UUID: {mdFileIdentifier}</em>
                                    </small>
                                </Col>
                            </Row>
                        </CardBody>
                    </Card>
                </div>
                <Col>
                    <Form class={$validateForm ? "was-validated" : ""}>
                        <div class="collapse" class:show={activeTab == "tab1"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">{localesView.tabs[1].title}</h3>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <!-- <Card class="mb-3">
                                        <CardBody> -->
                                    <!-- DONE: dataTitle -->
                                    <DataTitle field={localesView.fields.dataTitle} />
                                    <!-- DONE: dataAbstract -->
                                    <DataAbstract field={localesView.fields.dataAbstract} />
                                    <!-- DONE: dataTopicCategories -->
                                    <!-- <DataTopicCategories
                                                field={localesView.fields.dataTopicCategories}
                                                list={localesView.codelists.MD_TopicCategoryCode}
                                            /> -->
                                    <!-- TODO: DataThemeKeywords -->
                                    <DataThemeKeywords
                                        field={localesView.fields.dataThemeKeywords}
                                        list={localesView.codelists.MD_DataThemeKeywordCode}
                                    />
                                    <!-- DONE: dataKeywords -->
                                    <DataKeywords
                                        field={localesView.fields.dataKeywords}
                                        keywordTypes={localesView.codelists.MD_KeywordTypeCode}
                                        advancedMode={true}
                                    />
                                    <!-- </CardBody>
                                    </Card> -->

                                    <!-- <Card class="mb-3">
                                        <CardBody> -->
                                    <!-- DONE: dataBrowseGraphics -->
                                    <DataBrowseGraphics field={localesView.fields.dataBrowseGraphics} />
                                    <!-- </CardBody>
                                    </Card> -->

                                    <!-- <Card class="mb-3">
                                        <CardBody> -->
                                    <Row>
                                        <Col md="12" class="mb-3">
                                            <strong>Actualité et mise à jour des données</strong>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col md="8">
                                            <!-- DONE: DataDates -->
                                            <DataDates field={localesView.fields.dataDates} />
                                        </Col>
                                        <Col md="4">
                                            <!-- DONE: dataMaintenanceFrequency -->
                                            <DataMaintenanceFrequency
                                                field={localesView.fields.dataMaintenanceFrequency}
                                                list={localesView.codelists.MD_MaintenanceFrequencyCode}
                                            />
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col>
                                            {#if advancedView}
                                                <!-- DONE: DataTemporalExtents -->
                                                <DataTemporalExtents field={localesView.fields.dataTemporalExtents} />
                                            {/if}
                                        </Col>
                                    </Row>
                                    <!-- </CardBody>
                                    </Card> -->
                                </Col>
                            </Row>
                        </div>
                        <div class="collapse" class:show={activeTab == "tab2"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[2].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <Row>
                                <Col>
                                    <!-- DONE: dataPointOfContacts -->
                                    <Contacts
                                        type="dataPointOfContacts"
                                        field={localesView.fields.dataPointOfContacts}
                                        roles={localesView.codelists.CI_RoleCode}
                                    />
                                </Col>
                            </Row>
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab3"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[3].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <Row>
                                <Col>
                                    <!-- DONE: DataGeographicExtents -->
                                    <DataGeographicExtents field={localesView.fields.dataGeographicExtents} />
                                    <!-- DONE: dataLiStatement -->
                                    <DataLiStatement field={localesView.fields.dataLiStatement} />
                                    {#if advancedView}
                                        <!-- DONE: dataUseLimitations -->
                                        <DataUseLimitations field={localesView.fields.dataUseLimitations} />
                                        <!-- DONE: dataCharacterSet -->
                                        <DataCharacterSet
                                            field={localesView.fields.dataCharacterSet}
                                            list={localesView.codelists.MD_CharacterSetCode}
                                        />
                                    {/if}
                                    {#if advancedView}
                                        <!-- DONE: dataLanguages -->
                                        <DataLanguages
                                            field={localesView.fields.dataLanguages}
                                            list={localesView.codelists.MD_LanguageCode}
                                        />
                                    {/if}
                                    <!-- DONE: dataDistributionFormat -->
                                    <DataDistributionFormats field={localesView.fields.dataDistributionFormats} />
                                </Col>
                            </Row>
                            <!-- </CardBody>
                            </Card> -->

                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <hr />
                            <Row class="mb-1">
                                <Col md="12" class="my-auto">
                                    <Label for="isGeoData">
                                        <strong>Données géographique:</strong>
                                    </Label>
                                    <FormGroup inline check>
                                        <Input
                                            type="switch"
                                            id="is-geo-data"
                                            name="isGeoData"
                                            label="oui"
                                            inline
                                            checked={$isGeoData}
                                            value={true}
                                            on:change={onChangeGeoData}
                                        />
                                    </FormGroup>
                                </Col>
                            </Row>
                            <Fade isOpen={$isGeoData}>
                                <!-- DONE: dataIdentifiers -->
                                <DataIdentifiers field={localesView.fields.dataIdentifiers} />
                                <!-- DONE: dataInspireKeywords -->
                                <DataInspireKeywords
                                    field={localesView.fields.dataInspireKeywords}
                                    list={localesView.codelists.MD_InspireTopicCategoryCode}
                                />
                                {#if advancedView}
                                    <!-- DONE: dataTopicCategories -->
                                    <DataTopicCategories
                                        field={localesView.fields.dataTopicCategories}
                                        list={localesView.codelists.MD_TopicCategoryCode}
                                    />
                                {/if}
                                <!-- DONE: dataSpatialRepresentationType -->
                                <DataSpatialRepresentationType
                                    field={localesView.fields.dataSpatialRepresentationType}
                                    spatialRepresentationTypes={localesView.codelists.MD_SpatialRepresentationTypeCode}
                                />
                                <!-- DONE: dataReferenceSystems -->
                                <DataReferenceSystems
                                    field={localesView.fields.dataReferenceSystems}
                                    list={localesView.codelists.MD_ReferenceSystemCode}
                                />
                                <!-- DONE: dataSpatialResolution -->
                                <DataSpatialResolution field={localesView.fields.dataSpatialResolution} />
                            </Fade>
                            <!-- <DataSpatialResolution field={localesView.fields.dataSpatialResolution} /> -->
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab4"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[4].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <Row class="mb-3">
                                <Col md="12" class="my-auto">
                                    <!-- DONE: dataSecurityClassification -->
                                    <!-- <DataSecurityClassification
                                            field={localesView.fields
                                                .dataSecurityClassification}
                                            list={localesView.codelists
                                                .MD_ClassificationCode}
                                        /> -->
                                    <!-- DONE: dataLegalConstraints -->
                                    <DataLegalConstraints
                                        field={localesView.fields.dataLegalConstraints}
                                        listLicenses={localesView.codelists.Licenses}
                                        listClassificationCode={localesView.codelists.MD_ClassificationCode}
                                        listRestrictionCode={localesView.codelists.MD_RestrictionCode}
                                        listInspireRestrictionCode={localesView.codelists.MD_InspireRestrictionCode}
                                    />
                                </Col>
                            </Row>
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab5"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[5].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <!-- DONE: dataLinkages -->
                            <DataLinkages
                                field={localesView.fields.dataLinkages}
                                listProtocols={localesView.codelists.MD_LinkageProtocolCode}
                            />
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab6"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[6].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <p>
                                <strong> TODO: conformité: conformities/inspireConformities custom </strong>
                            </p>
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab8"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[8].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <!-- DONE: mdContacts -->
                            <Contacts
                                type="mdContacts"
                                field={localesView.fields.mdContacts}
                                roles={localesView.codelists.CI_RoleCode}
                            />
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                        <div class="collapse" class:show={activeTab == "tab9"}>
                            <Row>
                                <Col>
                                    <Button
                                        outline
                                        color="dark"
                                        size="sm"
                                        on:click={(e) => {
                                            onChangeSidebarView(e);
                                        }}
                                        class="float-start me-2"
                                    >
                                        <Icon name={viewMenu ? "chevron-bar-left" : "chevron-bar-right"} />
                                    </Button>
                                    <h3 class="mb-3">
                                        {localesView.tabs[9].title}
                                        {#if dataTitle}
                                            <em class="h6 text-muted ms-2">({dataTitle})</em>
                                        {/if}
                                    </h3>
                                </Col>
                            </Row>
                            <!-- <Card class="mb-3">
                                <CardBody> -->
                            <!-- DONE: mdFileIdentifier -->
                            <MdFileIdentifier field={localesView.fields.mdFileIdentifier} />
                            <!-- DONE: mdParentIdentifier -->
                            <MdParentIdentifier field={localesView.fields.mdParentIdentifier} />
                            <!-- DONE: mdLanguage -->
                            <MdLanguage
                                field={localesView.fields.mdLanguage}
                                list={localesView.codelists.MD_LanguageCode}
                            />
                            <!-- DONE: mdHierarchyLevel -->
                            <MdHierarchyLevel
                                field={localesView.fields.mdHierarchyLevel}
                                list={localesView.codelists.MD_ScopeCode}
                            />
                            <!-- DONE: mdCharacterSet -->
                            <MdCharacterSet
                                field={localesView.fields.mdCharacterSet}
                                list={localesView.codelists.MD_CharacterSetCode}
                            />
                            <!-- DONE: mdDateStamp -->
                            <MdDateStamp field={localesView.fields.mdDateStamp} />
                            <!-- DONE: mdStandardName -->
                            <MdStandardName field={localesView.fields.mdStandardName} />
                            <!-- DONE: mdStandardVersion -->
                            <MdStandardVersion field={localesView.fields.mdStandardVersion} />
                            <!-- </CardBody>
                            </Card> -->
                        </div>
                    </Form>
                </Col>
            </Row>

            <div class="toast-container position-fixed bottom-0 end-0 me-3 my-5 pb-4">
                {#each messages as message}
                    <Toast isOpen={message.open} class="bg-white" autohide={message.autohide}>
                        <ToastHeader
                            icon={message.icon}
                            toggle={() => {
                                message.open = false;
                            }}>{message.title}</ToastHeader
                        >
                        <ToastBody>
                            {message.content}
                        </ToastBody>
                    </Toast>
                {/each}
            </div>
            {#if $storeConfig.app.debug}
                <pre>{JSON.stringify($storeMdjs, false, 2)}</pre>
            {/if}
        </div>
    </Container>
{/if}
