<script>
    import { onMount } from "svelte";
    import { pop, replace, location, querystring, push } from "svelte-spa-router";
    import {
        Row,
        Col,
        Card,
        CardBody,
        Badge,
        Container,
        Button,
        Icon,
        Collapse,
        Fade,
        Nav,
        Navbar,
        NavbarBrand,
        ButtonToolbar,
        ButtonDropdown,
        DropdownItem,
        DropdownToggle,
        DropdownMenu,
    } from "sveltestrap/src/index.js";

    import helpers from "@/libs/helpers";
    import { storeConfig, storeLang, storeLocalesViews, storeModel, storeFile } from "@/stores/config.store";
    import { user } from "@/stores/app.store";
    import { storeMdjs } from "@/stores/mdjs.store";
    import { XmlConverter } from "@/libs/xml-converter/xml-converter";

    const converter = new XmlConverter();

    // let query;
    // let href;
    let dataTitle;
    let dataAbstract;
    let dataPointOfContacts;
    let dataResourceConstraints;
    let dataLiStatement;
    let dataSpatialRepresentationType;
    let bbox;
    let dataReferenceSystem;
    let dataScaleDistance;
    let dataScaleDenominator;
    let dataKeywords;
    let image;
    let isOpenData;
    let dataTopicCategories;
    let dataMaintenanceFrequency;
    let dataDate;

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

    $: isReady = localesView;
    $: mdUrl = helpers.getUrlParameter($querystring, "xml", false);
    // $: {
    //     if (href) {
    //         // replace([href, query].join("?"));
    //         replace(query ? [href, query].join("?") : href);
    //     }
    // }
    $: storeFile.setFile(mdUrl, "url", "xml");
    $: dataTitle = converter.getValue($storeMdjs, "dataTitle")[0] || "";
    $: dataAbstract = converter.getValue($storeMdjs, "dataAbstract")[0] || "";
    $: {
        const contacts = converter.getValue($storeMdjs, "dataPointOfContacts") || [];
        dataPointOfContacts = getContacts(contacts);
    }
    $: orgsList = dataPointOfContacts
        .filter((contact, index, contacts) => contacts.findIndex((c) => c.org === contact.org) === index)
        .map((contact) => contact.org);
    $: dataResourceConstraints = getResourceConstraints($storeMdjs);
    $: dataReferenceSystem = getReferenceSystem($storeMdjs);
    $: dataSpatialRepresentationType = converter.getValue($storeMdjs, "dataSpatialRepresentationType")[0] || "";
    $: bbox = getBbox($storeMdjs);
    $: dataLiStatement = converter.getValue($storeMdjs, "dataLiStatement")[0] || "";
    $: dataScaleDenominator = converter.getValue($storeMdjs, "dataScaleDenominator")[0] || "";
    $: dataScaleDistance = converter.getValue($storeMdjs, "dataScaleDistance")[0] || "";
    $: dataKeywords = converter.getValue($storeMdjs, "dataKeywordsList") || [];
    $: image = getImage($storeMdjs);
    $: isOpenData = helpers.arrayInArray(["opendata", "open data", "donnée ouverte", "données ouvertes"], dataKeywords);
    $: dataTopicCategories = converter.getValue($storeMdjs, "dataTopicCategories") || [];
    $: dataMaintenanceFrequency = converter.getValue($storeMdjs, "dataMaintenanceFrequency")[0] || "";
    $: dataDate = getDataDate($storeMdjs);

    const view = "view";
    $: localesView = $storeLocalesViews[view];

    onMount(() => {
        // query = helpers.checkQueryParams($querystring, { lang: $storeLang });
        // query = helpers.checkQueryParams($querystring);
        // href = $location == "/form" ? "/form/data" : $location;

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

    $: params = helpers.parseQueryString($querystring);
    $: {
        storeModel.setModel(params["model"]);
    }

    function getDataDate(mdjs) {
        var dataDates = mdjs ? converter.getValue(mdjs, "dataDates") : [{}];
        var dates = {};
        for (var i = 0; i < dataDates.length; i++) {
            var dateType = converter.getValue(dataDates[i], "dateType");
            if (dateType) {
                dates[dateType] = dataDates[i];
            }
        }
        return converter.getValue(dates.revision, "date")[0] || converter.getValue(dates.creation, "date")[0];
    }

    function getContacts(contacts) {
        var results = [];
        for (var c = 0; c < contacts.length; c++) {
            var result = {
                org: converter.getValue(contacts[c], "organisationName")[0] || "",
                email: converter.getValue(contacts[c], "emails")[0] || "",
                address: converter.getValue(contacts[c], "deliveryPoints").join(" - ") || "",
                city: converter.getValue(contacts[c], "city")[0] || "",
                postalcode: converter.getValue(contacts[c], "postalCode")[0] || "",
                logo: converter.getValue(contacts[c], "logoUrl")[0] || "",
                phone: converter.getValue(contacts[c], "phoneVoices")[0] || "",
            };
            results.push(result);
        }
        return results;
    }

    function getResourceConstraints(mdjs) {
        var results = {
            useLimitations: [],
            legalUseLimitations: [],
            legalUseConstraints: [],
            legalAccessConstraints: [],
            legalOtherConstraints: [],
            securityClassification: [],
        };
        var constraints = converter.getValue(mdjs, "dataResourceConstraints") || [];
        for (var c = 0; c < constraints.length; c++) {
            var useLimitations = converter.getValue(constraints[c], "dataUseLimitations") || [];
            var legalUseLimitations = converter.getValue(constraints[c], "dataLegalUseLimitations") || [];
            var legalUseConstraints = helpers.cleanArray(
                converter.getValue(constraints[c], "dataLegalUseConstraints") || []
            );
            var legalAccessConstraints = helpers.cleanArray(
                converter.getValue(constraints[c], "dataLegalAccessConstraints") || []
            );
            var legalOtherConstraints = helpers.cleanArray(
                converter.getValue(constraints[c], "dataLegalOtherConstraints") || []
            );
            var securityClassification = helpers.cleanArray(
                converter.getValue(constraints[c], "dataSecurityClassification") || []
            )[0];

            results.useLimitations = useLimitations.length
                ? results.useLimitations.concat(useLimitations)
                : results.useLimitations;
            results.legalUseLimitations = legalUseLimitations.length
                ? results.legalUseLimitations.concat(legalUseLimitations)
                : results.legalUseLimitations;
            results.legalUseConstraints = legalUseConstraints.length
                ? results.legalUseConstraints.concat(legalUseConstraints)
                : results.legalUseConstraints;
            results.legalAccessConstraints = legalAccessConstraints.length
                ? results.legalAccessConstraints.concat(legalAccessConstraints)
                : results.legalAccessConstraints;
            results.legalOtherConstraints = legalOtherConstraints.length
                ? results.legalOtherConstraints.concat(legalOtherConstraints)
                : results.legalOtherConstraints;
            results.securityClassification = securityClassification
                ? securityClassification
                : results.securityClassification;
        }
        return results;
    }

    function getBbox(mdjs) {
        var results = [];
        const extents = converter.getValue(mdjs, "dataExtents") || [];
        for (var e = 0; e < extents.length; e++) {
            var result = { name: converter.getValue(extents[e], "extentName")[0] || "" };
            const bbox = converter.getValue(extents[e], "geographicExtent") || [];
            if (bbox.length) {
                result.west = converter.getValue(extents[e], "geographicExtentWestBound")[0] || "";
                result.east = converter.getValue(extents[e], "geographicExtentEastBound")[0] || "";
                result.south = converter.getValue(extents[e], "geographicExtentSouthBound")[0] || "";
                result.north = converter.getValue(extents[e], "geographicExtentNorthBound")[0] || "";
                results.push(result);
            }
        }
        return results;
    }
    function getReferenceSystem(mdjs) {
        var dataReferenceSystems = converter.getValue(mdjs, "dataReferenceSystems") || [];
        return converter.getValue(dataReferenceSystems[0], "referenceSystemCode") || "";
    }

    function getImage(mdjs) {
        var image = converter.getValue(mdjs, "dataBrowseGraphics")[0] || [];
        return {
            format: converter.getValue(image, "fileType")[0] || "",
            url: converter.getValue(image, "fileName")[0] || "",
            description: converter.getValue(image, "fileDescription")[0] || "",
        };
    }

    function onPrint() {
        window.print();
    }

    function onClose() {
        // window.history.back();
        pop();
    }

    function goTo(href) {
        push(href);
    }

    function onSave(org) {
        console.log("save XML");
    }
</script>

{#if isReady}
    <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>

                {#if $user.editor}
                    {#if $user.orgs.length == 1}
                        <Button
                            outline
                            color="dark"
                            on:click={() => {
                                onSave();
                            }}>Enregistrer</Button
                        >
                    {:else}
                        <ButtonDropdown>
                            <DropdownToggle outline color="dark" caret>Fiche</DropdownToggle>
                            <DropdownMenu>
                                {#each $user.orgs as org}
                                    <DropdownItem
                                        on:click={() => {
                                            onSave(org);
                                        }}>Enregistrer dans {org.name}</DropdownItem
                                    >
                                {/each}
                            </DropdownMenu>
                        </ButtonDropdown>
                    {/if}
                {/if}
            </ButtonToolbar>
        </Nav>
    </Navbar>

    <Container class="py-3">
        <Row class="mt-1 ms-1">
            <Col md="12" class="d-flex">
                <div>
                    <Button class="d-print-none pl-2 text-secondary bg-white text-muted border-0" on:click={onClose}>
                        <Icon name="caret-left" />
                        Retour
                    </Button>
                    <span class="p-3 border-right border-primary" />
                </div>
                <div class="flex-grow-1">
                    <h1 class="ms-5 mt-n3 h5 font-weight-bold">
                        {#if dataTitle}
                            {dataTitle}
                        {:else}
                            Titre des données non renseigné
                        {/if}
                    </h1>
                    <div class="ms-5">
                        {orgsList.join(", ")}
                    </div>
                </div>
            </Col>
        </Row>

        <Row class="mt-3">
            <Col xs="12" sm="12" md="7" lg="8" xl="9" class="pr-0">
                <Card class="m-1 mb-4">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Description</small>
                        </div>
                        {#if dataAbstract}
                            <div>{@html helpers.nl2br(dataAbstract)}</div>
                        {:else}
                            Aucune description des données renseigné
                        {/if}
                    </CardBody>
                </Card>
                <Card class="m-1 mb-4">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Limites techniques d'usage</small>
                        </div>
                        <div>
                            <ul class="m-0">
                                {#if dataResourceConstraints.useLimitations.length}
                                    {#each dataResourceConstraints.useLimitations as useLimitation}
                                        <li>{useLimitation}</li>
                                    {/each}
                                {:else}
                                    <li>Aucune limite technique d'usage des données renseignée</li>
                                {/if}
                            </ul>
                        </div>
                    </CardBody>
                </Card>
                <Card class="m-1 mb-4">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Licences et conditions d'utilisation</small>
                        </div>
                        <div>
                            <ul class="m-0">
                                {#if dataResourceConstraints.legalUseLimitations.length}
                                    {#each dataResourceConstraints.legalUseLimitations as legalUseLimitation}
                                        <li>{legalUseLimitation}</li>
                                    {/each}
                                {/if}
                                {#if dataResourceConstraints.legalOtherConstraints.length}
                                    {#each dataResourceConstraints.legalOtherConstraints as legalOtherConstraint}
                                        <li>{legalOtherConstraint}</li>
                                    {/each}
                                {/if}
                                {#if !dataResourceConstraints.legalOtherConstraints.length && !dataResourceConstraints.legalUseLimitations.length}
                                    <li>Aucune licence ou limite d'utilisation renseignée</li>
                                {/if}
                            </ul>
                        </div>
                    </CardBody>
                </Card>
                <Card class="m-1 mb-3">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Méthode de production et qualité</small>
                        </div>
                        {#if dataLiStatement}
                            {@html helpers.nl2br(dataLiStatement)}
                        {:else}
                            Aucune information sur la qualité des données renseignée.
                        {/if}
                    </CardBody>
                </Card>
                <Card class="m-1 mb-3">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Informations géographiques</small>
                        </div>
                        <Row>
                            <Col>
                                <p>
                                    <strong>Type de représentation:</strong>
                                    {#if dataSpatialRepresentationType}
                                        {helpers.translateValue(
                                            dataSpatialRepresentationType,
                                            localesView.codelists.MD_SpatialRepresentationTypeCode
                                        )}
                                    {:else}
                                        non renseignée
                                    {/if}
                                </p>
                                {#each bbox as bb}
                                    <p>
                                        <strong>Etendue géographique:</strong>
                                        {bb.name}
                                    </p>
                                    <ul>
                                        <li>Ouest: {bb.west}</li>
                                        <li>Est: {bb.east}</li>
                                        <li>Sud: {bb.south}</li>
                                        <li>Nord: {bb.north}</li>
                                    </ul>
                                {/each}
                            </Col>
                            <Col>
                                <p>
                                    <strong>Système de projection:</strong>
                                    {#if dataReferenceSystem}
                                        {dataReferenceSystem}
                                    {:else}
                                        non renseignée
                                    {/if}
                                </p>
                                <p>
                                    <strong>Echelle:</strong>
                                    {#if dataScaleDenominator}
                                        1/{dataScaleDenominator}
                                    {:else}
                                        non renseignée
                                    {/if}
                                </p>
                                <p>
                                    <strong>Résolution:</strong>
                                    {#if dataScaleDistance}
                                        {dataScaleDistance}
                                    {:else}
                                        non renseignée
                                    {/if}
                                </p>
                            </Col>
                        </Row>
                    </CardBody>
                </Card>
                <Card class="m-1 mb-5">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Mots-clés</small>
                        </div>
                        <div>
                            {#each dataKeywords as keyword}
                                <Badge color="primary" class="me-2 px-2 py-1 text-uppercase">
                                    {keyword}
                                </Badge>
                            {:else}
                                Aucun mot-clé renseigné
                            {/each}
                        </div>
                    </CardBody>
                </Card>
            </Col>
            <Col xs="12" sm="12" md="5" lg="4" xl="3">
                <Card no-body class="m-1 mb-3">
                    <img src={image.url ? image.url : "images/no-picture.jpg"} alt="Overview" />
                </Card>
                <Card class="m-1 mb-3">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Synthèse</small>
                        </div>
                        <div class="my-3">
                            <Button color={isOpenData ? "success" : "danger"} size="sm" active class="text-white">
                                <Icon name={isOpenData ? "unlock-fill" : "lock-fill"} />
                            </Button>
                            {#if isOpenData}
                                <span class="ms-2">Données ouvertes</span>
                            {:else}
                                <span class="ms-2">Accès restreint</span>
                            {/if}
                        </div>
                        <div class="my-3">
                            <Button
                                color={dataSpatialRepresentationType ? "primary" : "warning"}
                                size="sm"
                                active
                                class="text-white"
                            >
                                <Icon name={dataSpatialRepresentationType ? "geo-alt" : "graph-up"} />
                            </Button>
                            {#if dataSpatialRepresentationType}
                                <span class="ms-2">Donnée géographique</span>
                            {:else}
                                <span class="ms-2">Donnée non géographique</span>
                            {/if}
                        </div>
                        <div class="my-3">
                            <Button color="light" outline size="sm" active class="">
                                <Icon name="clock" />
                            </Button>
                            <span class="ms-2"
                                >Date des données:
                                {#if dataDate}
                                    {helpers.formatDate(dataDate, "DD/MM/YYYY")}
                                {:else}
                                    inconnue
                                {/if}
                            </span>
                        </div>
                        <div class="my-3">
                            <Button color="secondary" outline size="sm" active class="text-white">
                                <Icon name="hourglass-split" />
                            </Button>
                            <span class="ms-2"
                                >Fréquence de mise à jour
                                {#if dataMaintenanceFrequency}
                                    {helpers.translateValue(
                                        dataMaintenanceFrequency,
                                        localesView.codelists.MD_MaintenanceFrequencyCode
                                    )}
                                {:else}
                                    inconnue
                                {/if}
                            </span>
                        </div>
                        <div class="my-3">
                            <Button color="info" outline size="sm" active class="text-white">
                                <Icon name="tag" />
                            </Button>
                            {#if dataTopicCategories.length}
                                <span class="ms-2"
                                    >{helpers
                                        .translateArray(dataTopicCategories, localesView.codelists.MD_TopicCategoryCode)
                                        .join(", ")}</span
                                >
                            {:else}
                                <span class="ms-2">Aucune catégorie renseignée</span>
                            {/if}
                        </div>
                    </CardBody>
                </Card>
                <Card class="m-1 mb-3">
                    <CardBody>
                        <div class="h5 text-uppercase">
                            <small>Contacts</small>
                        </div>
                        <div class="list-unstyled">
                            {#each dataPointOfContacts as contact, contactId}
                                <div class="d-flex align-items-center mt-3">
                                    <div class="flex-shrink-0">
                                        <img
                                            src={contact.logo ? contact.logo : "images/no-picture.jpg"}
                                            width="96"
                                            alt={contact.org}
                                            class="me-3"
                                        />
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <strong id={"displayContact" + contactId}
                                            >{contact.org} <Icon name="chevron-expand" class="ms-1" /></strong
                                        >
                                        <p class="mb-0">
                                            <Icon name="envelope" class="me-2" /><a href={"mailto:" + contact.email}
                                                >contact</a
                                            >
                                        </p>
                                    </div>
                                </div>
                                <Fade toggler={"#displayContact" + contactId} class="mb-4">
                                    {#if contact.address}
                                        {contact.address} <br />
                                    {/if}
                                    {#if contact.postalcode || contact.city}
                                        {contact.postalcode}
                                        {contact.city} <br />
                                    {/if}
                                    {#if contact.phone}
                                        <Icon name="phone" class="me-2" /> Tél.: {contact.phone}
                                    {/if}
                                </Fade>
                                <hr />
                            {/each}
                        </div>
                    </CardBody>
                </Card>
            </Col>
        </Row>
    </Container>
{/if}
