<script>
    import Paginate from "$/components/Paginate.svelte";
    import { downloadGtfsArchivo, getGtfsArchivo,getGtfsArchivoId,getGtfsBase } from "$/services/gtfs_archivo";
    import PageTitle from "$/components/PageTitle.svelte";    
    import { useLocation } from "svelte-navigator";
    import { getPermisosPath } from "$/services/usuarios";
    import ModalgtfsUpload from "./ModalgtfsUpload.svelte";
    import { getRedTransporte } from "$/services/red_transporte";
    import { space } from "svelte/internal";
     
    let id_red;  
    let escritura = false;

    const limit = 15;
    let page = 1;
    let offset = 0;
    let count = 0;
    let ordering = 'id_archivo'
    let redes = []
    let lista_gtfs = []
    let location = useLocation()
    let loading = false;
    let showUpload = null;
    getPermisosPath($location.pathname)
        .then(data => escritura = data.escritura)
        .catch(error => console.log({ error }))

    getRedTransporte({ vigente: 1, ordering: 'nombre_red' })
        .then(data => redes = data)
        .then(() => id_red = redes[0]?.id_red || null)
        .then(() => onPage(1))
        .catch(error => globalThis.toast.error(error))

    async function onPage(p) {
        try {
            if (!id_red) {         
                return;
            }
            loading = true
            offset = (p - 1) * limit;
            const data = await getGtfsArchivo({id_red, offset, limit, ordering })
            lista_gtfs = data.results;
            count = data.count;
        } catch (error) {
            globalThis.toast.error(error)
        } finally {
            loading = false;
        }
    }

    function onOrderBy(field) {
        ordering = ordering === field ? '-' + field : field;
        onPage(page)
    }

    function onChangeRed() {
        page = 1; // Reinicia la paginación al cambiar de red
        onPage(page);
    }

    function onNuevo() {
        showUpload = true
    }

    function onDownload({ id_gtfs }) {
        loading = true
        downloadGtfsArchivo(id_gtfs)
            .catch(error => globalThis.toast.error(error))
            .finally(() => loading = false)
    }

 

</script>

<PageTitle {loading}>Listado Archivos GTFS</PageTitle>

<div class="card">
    <div class="card-header">
        {#if escritura}
            <button class="btn btn-primary" on:click|preventDefault={onNuevo}>
                Cargar Archivo GTFS
            </button>
        {/if}
    </div>
    <div class="card-body">

        <div class="input-group mb-3">
            <div class="input-group-text">Red de Transporte</div>
            <select bind:value={id_red} class="form-select" on:change={onChangeRed}>
                <option value=""></option>
                {#each redes as rt}
                    <option value={rt.id_red}>{rt.nombre_red}</option>
                {/each}
            </select>
        </div>

        <div class="table-responsive">
            <table class="table table-sm table-bordered">
                <thead>
                    <tr class="table-light">
                        <th style="width: 5%">Nro</th>
                       <!-- <th style="width: 5%">
                            <a href={"#"} on:click|preventDefault={() => onOrderBy('id_gtfs')}>ID</a>
                            {#if ordering === 'id_gtfs'}<i class="bi bi-caret-up-fill"></i>{/if}
                            {#if ordering === '-id_gtfs'}<i class="bi bi-caret-down-fill"></i>{/if}
                        </th>-->
                        <th>
                            <a href={"#"} on:click|preventDefault={() => onOrderBy('nombre_red')}>Archivo</a>
                            {#if ordering === 'archivo'}<i class="bi bi-caret-up-fill"></i>{/if}
                            {#if ordering === '-archivo'}<i class="bi bi-caret-down-fill"></i>{/if}
                        </th>
                        
                        <th>
                            <a href={"#"} on:click|preventDefault={() => onOrderBy('created')}>Creado el</a>
                            {#if ordering === 'created'}<i class="bi bi-caret-up-fill"></i>{/if}
                            {#if ordering === '-created'}<i class="bi bi-caret-down-fill"></i>{/if}
                        </th>

                        <th>
                            <a href={"#"} on:click|preventDefault={() => onOrderBy('status')}>Estado</a>
                            {#if ordering === 'status'}<i class="bi bi-caret-up-fill"></i>{/if}
                            {#if ordering === '-status'}<i class="bi bi-caret-down-fill"></i>{/if}
                        </th>

                        <th>
                            <a href={"#"} on:click|preventDefault={() => onOrderBy('vigente')}>Vigente</a>
                            {#if ordering === 'vigente'}<i class="bi bi-caret-up-fill"></i>{/if}
                            {#if ordering === '-vigente'}<i class="bi bi-caret-down-fill"></i>{/if}
                        </th>
                    </tr>
                </thead>
                <tbody>
                    {#each lista_gtfs as app, index}
                    <tr>
                        <td class="table-light">{offset + index + 1}</td>
                        <!--<td>{app.id_gtfs}</td>-->
                        <td>
                            {#if !loading}
                                <a href={"#"} on:click|preventDefault={() => onDownload(app)}>{app.archivo}</a>
                            {:else}
                                <span>{app.archivo}</span>
                            {/if}
                        </td>
                        <td>{app.created}</td>
                        <td>{app.status}</td>
                        <td>{app.vigente ? '✅':'🚫'}</td>
                    </tr>
                    {/each}
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer d-flex">
        <a href={"#"} class="btn btn-outline-secondary me-3" on:click|preventDefault={() => onPage(page)}>
            <i class="bi bi-arrow-repeat"></i>
        </a>
        <Paginate
            forcePage={page}
            {limit}
            {count}
            on:page={ev => page = ev.detail}
        />
    </div>
</div>

{#if showUpload}
    <ModalgtfsUpload on:close={() => showUpload = false} {id_red} on:refresh={() => onPage(page)} />
        
{/if}

<style>
    .table-responsive {
        max-height: calc(100vh - 300px);
    }
</style>