<script>
    import { Link, useLocation } from 'svelte-navigator'
    import Paginate from '$/components/Paginate.svelte'
    import { getPersonas } from '$/services/personas';
    import PageTitle from '$/components/PageTitle.svelte';
    import { getPermisosPath } from '$/services/usuarios';
    import { storePermisoApp } from '$/stores/global';

    let page = 1;
    let limit = 15;
    let personas = { results: [], count: 0 };
    let loading = false;
    let escritura = false;
    let location = useLocation()

    getPermisosPath($location.pathname)
        .then(data => escritura = data.escritura)
        .then(() => storePermisoApp.set({ ...$storePermisoApp, personas: { escritura } }))
        .catch(error => console.log({ error }))

    $: onPage(page)

    async function onPage(page) {
        try {
            loading = true
            const offset = (page - 1) * limit;
            personas = await getPersonas({ offset, limit })
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        } finally {
            loading = false;
        }
    }
</script>

<PageTitle {loading}>Personas</PageTitle>

<div class="card">
    <div class="card-header">
        {#if escritura}
            <Link to='/personas/nuevo' class="btn btn-primary">
                <i class="bi bi-plus-lg"></i> Nuevo
            </Link>
        {/if}
    </div>
    <div class="card-body">
        <table class="table table-sm">
            <thead>
                <tr>
                    <th>RUT</th>
                    <th>Nombres</th>
                    <th>Apellido 1</th>
                    <th>Apellido 2</th>
                    <th>Teléfono</th>
                </tr>
            </thead>
            <tbody>
                {#each personas.results as p}
                <tr>
                    <td><Link to={'/personas/' + p.rut}>{p.rut}-{p.dv}</Link></td>
                    <td>{p.nombres}</td>
                    <td>{p.apellido_a}</td>
                    <td>{p.apellido_b}</td>
                    <td>{p.fono}</td>
                </tr>
                {/each}
            </tbody>
        </table>
    </div>
    <div class="card-footer">
        <Paginate
            forcePage={page}
            {limit}
            count={personas.count}
            on:page={ev => page = ev.detail}
        />
    </div>
</div>