<script>
    import { onMount } from "svelte";
    import { querystring, location, replace, push } from "svelte-spa-router";
    import { Button, ButtonToolbar, Container, Col, Fade, Icon, Input, Label, Row, Table } from "sveltestrap";

    import helpers from "@/libs/helpers/index.js";
    import { storeConfig, storeLang, storeLocalesViews, storeModel, storeFile } from "@/stores/config.store";
    import { user } from "@/stores/app.store";
    import { storeFiles, storeUrlFiles, storeDeletedFiles, storeNewFiles } from "@/stores/files.store";

    $: isReady = localesView;

    let directories = false;
    let search = "";
    let loading = 0;
    let displayList = [];
    // let query;
    // Update URL when query is modified
    // $: {
    //     // replace([$location, query].join("?"));
    //     replace(query ? [$location, query].join("?") : $location);
    // }

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

    onMount(() => {
        if (!$user.editor) {
            push("/?" + $querystring);
            // window.location = "/?" + $querystring;
        }

        // query = helpers.checkQueryParams($querystring, { lang: $storeLang });
        // query = helpers.checkQueryParams($querystring);

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

        getData();
    });

    function getData() {
        // Get files
        loading++;
        fetch($storeConfig.api.files)
            .then(function (response) {
                return response.json();
            })
            .then(function (json) {
                directories = json.directories;
                loading--;
                directories = checkFiles(directories);
                displayList = Array(directories.length).fill(true);
            })
            .catch(function (error) {
                console.log("Fetch error: " + error.message);
                loading--;
            });
    }

    function checkFiles(directories) {
        for (let d = 0, n = directories.length; d < n; d++) {
            let directory = directories[d];
            for (let f = 0, n = directory.files.length; f < n; f++) {
                let file = directory.files[f];
                directories[d].files[f].valid =
                    file.file == directory.name + "/" + file.fileIdentifier + "/" + file.fileIdentifier + ".xml";
            }
        }
        return directories;
    }

    $: filteredDirectories = filterFiles(directories, search);

    // TODO: Voir pour mixer checkFiles() et filterFiles()
    function filterFiles(directories, search) {
        let directoriesCopy = JSON.parse(JSON.stringify(directories));
        for (let d = 0, n = directories.length; d < n; d++) {
            directoriesCopy[d].files = [];
            for (let f = 0, n = directories[d].files.length; f < n; f++) {
                let file = directories[d].files[f];
                if (file) {
                    if (
                        !search ||
                        [file.filename, file.fileIdentifier, file.dataTitle]
                            .join(" ")
                            .toLocaleLowerCase()
                            .includes(search.toLocaleLowerCase())
                    ) {
                        directoriesCopy[d].files.push(file);
                    }
                }
            }
        }
        return directoriesCopy;
    }

    function goBackHome() {
        push("/");
    }

    function onDeleteFile(e, file) {
        e.preventDefault();
        var response = confirm(
            [
                "Voulez-vous vraiment supprimer le fichier '" +
                    file.filename +
                    ".xml' ainsi que le dossier '/" +
                    file.filename +
                    "' associé ?",
                "Fiche: " + file.dataTitle + " (" + file.fileIdentifier + ")",
            ].join("\n")
        );
        if (response == true) {
            var path = file.path.replace(/\\/g, "/");
            var url = $storeConfig.api.directories + "&directories=" + file.path;
            fetch(url, {
                method: "DELETE",
            })
                .then((response) => response.json())
                .then((json) => {
                    getData();
                });
        }
    }

    function onLoadFile(e, file) {
        e.preventDefault();
        // Empty files stores
        $storeFiles = [];
        $storeUrlFiles = [];
        $storeDeletedFiles = [];
        $storeNewFiles = [];

        var url = $storeConfig.api.files + "&file=" + file.file;
        storeFile.setFile(url, "url");
        // push("/form/data");
        push("/formdata");
    }

    function onViewFile(e, file) {
        e.preventDefault();
        var url = $storeConfig.api.files + "&file=" + file.file;
        storeFile.setFile(url, "url");
        push("/view");
    }

    function formatDate(date, format) {
        return helpers.formatDate(date, format);
    }
</script>

{#if isReady}
    <Container class="mt-2">
        <Row>
            <Col>
                <ButtonToolbar class="mt-3">
                    <Button outline color="dark" class="me-3" on:click={goBackHome}>Retour</Button>
                </ButtonToolbar>
                <!-- <Button class="d-print-none pl-2 text-secondary bg-white text-muted border-0" on:click={goBackHome}>
            <Icon name="caret-left" />
            Retour
        </Button> -->
            </Col>
            <Col>
                <div class="float-end w-75 mt-3">
                    <!-- <input bind:value={search} type="text" id="searchInput"> -->
                    <Input bind:value={search} type="search" id="searchInput" placeholder="Filtrer les listes" />
                </div>
            </Col>
        </Row>
        <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"
                            >Chargement des fiches...<br />Cela peut prendre un moment. Merci de patienter.</small
                        >
                    </div>
                </div>
            </div>
        </div>
        <div hidden={loading}>
            {#if filteredDirectories}
                {#each filteredDirectories as dir, dirId}
                    <div class="my-4">
                        <Icon name="folder-fill" class="me-3" />
                        <strong>{dirId + 1} - Dépôts "{dir.name}"</strong>
                        <ButtonToolbar class="float-end">
                            <Button
                                color="primary"
                                class="mx-1"
                                on:click={() => {
                                    push("/formdata");
                                }}
                            >
                                <Icon name="plus" />
                            </Button>
                            <Button
                                color="dark"
                                outline
                                class="mx-1"
                                on:click={() => (displayList[dirId] = !displayList[dirId])}
                            >
                                <Icon name={displayList[dirId] ? "chevron-up" : "chevron-down"} />
                            </Button>
                        </ButtonToolbar>
                    </div>

                    <div class="mt-4 mb-5">
                        <Fade isOpen={displayList[dirId]}>
                            <!-- <div class="collapse" class:show={displayList[dirId]}> -->
                            {#if dir.files.length}
                                <Table hover>
                                    <thead>
                                        <tr class="d-flex">
                                            <th class="col-1 text-center" scope="col">#</th>
                                            <th class="col-7 text-center" scope="col">Fichier</th>
                                            <th class="col-2 text-center" scope="col">Modification</th>
                                            <th class="col-2 text-center" scope="col">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {#each dir.files as file, fileId}
                                            {#if file.fileIdentifier}
                                                <tr class="d-flex">
                                                    <td class="col-1 d-flex justify-content-center align-items-center">
                                                        {fileId + 1}
                                                    </td>
                                                    <td class="col-7">
                                                        {#if file.valid}
                                                            <a
                                                                href="#/"
                                                                class="link-dark h6"
                                                                title={file.filename}
                                                                on:click={(e) => {
                                                                    onLoadFile(e, file);
                                                                }}
                                                            >
                                                                <Icon
                                                                    name="file-earmark-code-fill"
                                                                    class="me-2 text-success"
                                                                />{#if file.dataTitle}{file.dataTitle}
                                                                {:else}Titre non défini
                                                                {/if}
                                                            </a>
                                                        {:else}
                                                            <span title="Ce fichier ne peut pas être édité">
                                                                <Icon
                                                                    name="file-earmark-code-fill"
                                                                    class="me-2 text-danger"
                                                                />
                                                                {#if file.dataTitle}{file.dataTitle}
                                                                {:else}Titre non défini
                                                                {/if}
                                                            </span>
                                                        {/if}
                                                        <div class="small font-weight-light" title={file.filename}>
                                                            Fichier: {file.basename}<br />
                                                            {#if file.fileIdentifier}
                                                                Identifiant: {file.fileIdentifier}
                                                            {/if}
                                                        </div>
                                                    </td>
                                                    <td class="col-2 d-flex justify-content-center align-items-center">
                                                        <!-- TODO: format date -->
                                                        {formatDate(new Date(file.mtime * 1000), "DD/MM/YYYY hh:mm:ss")}
                                                    </td>
                                                    <td
                                                        class="col-2 d-md-flex justify-content-center align-items-center"
                                                    >
                                                        {#if file.valid}
                                                            <Button
                                                                outline
                                                                size=""
                                                                color="danger"
                                                                class="me-2"
                                                                on:click={(e) => {
                                                                    onDeleteFile(e, file);
                                                                }}><Icon name="trash" /></Button
                                                            >
                                                            <Button
                                                                outline
                                                                size=""
                                                                color="primary"
                                                                class="me-2"
                                                                on:click={(e) => {
                                                                    onLoadFile(e, file);
                                                                }}><Icon name="pencil" /></Button
                                                            >
                                                        {/if}
                                                        <Button
                                                            outline
                                                            size=""
                                                            color="success"
                                                            class="me-2"
                                                            on:click={(e) => {
                                                                onViewFile(e, file);
                                                            }}><Icon name="eye" /></Button
                                                        >
                                                    </td>
                                                </tr>
                                            {/if}
                                        {/each}
                                    </tbody>
                                </Table>
                            {:else}
                                <Row>
                                    <Col>
                                        <p class="h5 text-center">
                                            Aucune fiche de métadonnées disponible dans ce répertoire
                                        </p>
                                    </Col>
                                </Row>
                            {/if}
                        </Fade>
                        <!-- </div> -->
                    </div>
                {/each}
            {:else}
                <Row>
                    <Col>
                        <p class="h5 text-center my-5">Aucun dossier ou fichier disponible</p>
                    </Col>
                </Row>
            {/if}

            <Row>
                <Col>
                    <ButtonToolbar class="float-end mb-5">
                        <Button outline color="dark" class="me-3" on:click={goBackHome}>Retour</Button>
                    </ButtonToolbar>
                </Col>
            </Row>
        </div>
    </Container>
{/if}
