<script>
    import IconLoading from "../../components/IconLoading.svelte";
import Modal from "../../components/Modal.svelte";
    import { createLetreroLUR, deleteLetreroLUR } from "../../services/letreros_lur";
    import { createLinea, deleteLinea, updateLinea } from "../../services/lineas";
    import FormRuta from "./FormRuta.svelte";
    import { createEventDispatcher } from "svelte";
    const dispatch = createEventDispatcher()

    export let ruta = null;
    let form = {}
    let error_messages = null;
    let loading = false

    $: form = { ...ruta }

    async function onSave() {
        try {
            loading = true
            error_messages = null
            const { id_linea } = ruta;
            const { route_short_name, route_long_name,
                linea1, linea2, linea3, linea4,
                bgcolor1, color1, bgcolor2, color2
            } = form;
            if (id_linea) {
                await updateLinea({ id_linea, route_short_name, route_long_name })
            } else {
                await createLinea({ route_short_name, route_long_name })
            }

            await deleteLetreroLUR(route_short_name).catch(() => {})
            await createLetreroLUR({
                codigo: route_short_name,
                linea1, linea2, linea3, linea4,
                bgcolor1, color1, bgcolor2, color2
            })
            dispatch('close')
        } catch (error) {
            const data = JSON.parse(error) || null
            if (data) error_messages = data;
            console.log({ data })
        } finally {
            loading = false
        }
    }

    // async function onDelete() {
    //     try {
    //         const { id_linea, route_short_name } = ruta;
    //         await deleteLetreroLUR(route_short_name)
    //         await deleteLinea(id_linea)
    //         dispatch('close')
    //     } catch (error) {
    //         console.log({ error })
    //     }
    // }
</script>

<form on:submit|preventDefault={onSave}>
    <Modal title="Ruta de Servicio" size="xl"
        on:close={() => dispatch('close')}
    >
        <FormRuta {form} />
    
        {#if error_messages}
            <div class="alert alert-danger">
                <ul>
                    {#each Object.entries(error_messages) as [field, message]}
                    <li>{field}: {message[0]}</li>
                    {/each}
                </ul>
            </div>
        {/if}
    
        <svelte:fragment slot="buttons">
            <button class="btn btn-primary" type="submit" disabled={loading}><i class="bi bi-save"></i> Guardar</button>
            <!-- {#if ruta.id_linea}
                <button class="btn btn-danger" on:click|preventDefault={onDelete}><i class="bi bi-trash"></i> Eliminar</button>
            {/if} -->

            {#if loading}<IconLoading />{/if}
        </svelte:fragment>
    </Modal>
</form>