<script>
    import Modal from "../../components/Modal.svelte";
    import {
        getOperador,
        createOperador,
        updateOperador,
        deleteOperador,
    } from "$/services/operadores";
    import {        
        createRol       
    }
    from  "$/services/roles";
    import {       
        createRolOperador
    }
    from  "$/services/roles_operadores";
    import {       
        createRolyaplicacion
    }
    from  "$/services/roles_aplicaciones";
    import { createEventDispatcher } from "svelte";
    import TabOperador from "./TabOperador.svelte";
    import "./modal.css";
    import TabLineas from "./TabLineas.svelte";
    import { getLineas, updateLinea } from "$/services/lineas";
    const dispatch = createEventDispatcher();

    export let operador = {};
    export let escritura = false;
    let form = { vigente: true };
    let lineas = []
    let loading = false;
    let tab = 0;


    $: tab === 0 && begin(operador.id_operador);
    $: tab === 1 && fetchLineas()

    async function begin(id) {
        try {
            if (!id) return;
            form = (await getOperador(id)) || {};
        } catch (error) {
            globalThis.toast.success(error.detail || error);
        }
    }

    async function fetchLineas() {
        try {
            lineas = []
            const data = await getLineas({ vigente:true, ordering: 'route_long_name' })
            lineas = data.filter(linea => 
            linea.id_operador === operador.id_operador || linea.id_operador === null
            );
            lineas = lineas.map(linea => ({
                ...linea,
                activo: linea.id_operador == operador.id_operador,  
                modificado: false,
            }));        
        } catch (error) {
            globalThis.toast.error(error.detail || error);
        }
    }


    async function onSave() {
       let formRol={}; 
        try {
            loading = true;
            if (operador.id_operador) {
                form = await updateOperador(form);
            } else {
                
                formRol.nombre_rol=form.nombre_operador;
                formRol = await createRol(formRol);
                form.id_rol = formRol.id_rol    
                form = await createOperador(form);                
                formRol= await createRolOperador(form);

                formRol={};
                formRol.id_rol = form.id_rol;
                formRol.id_aplicacion=1;
                formRol = await createRolyaplicacion(formRol);

                formRol.id_aplicacion=2;
                formRol = await createRolyaplicacion(formRol);


            }
            
            globalThis.toast.success("Se ha guardado el Operador");
            dispatch("refresh");
            dispatch("close");
        } catch (error) {
            globalThis.toast.error(error.detail || error);
        } finally {
            loading = false;
        }
    }

    async function onDelete() {
        try {
            if (!confirm("Eliminará el registro?")) return;
            loading = true;
            await deleteOperador(form.id_operador);
            globalThis.toast.success("Se ha eliminado el Operador");
            dispatch("refresh");
            dispatch("close");
        } catch (error) {
            globalThis.toast.error(error.detail || error);
        } finally {
            loading = false;
        }
    }

    async function onSaveLineas() {
        
        try {
            loading = true;
            
            const lineasModificadas = lineas.filter(linea => linea.modificado).map(linea => ({
                id_linea: linea.id_linea,
                id_operador: linea.activo ? operador.id_operador : null, // Establece id_operador basado en 'activo'.
            }));

            if (operador.id_operador) {
                for (let ln of lineasModificadas) {
                    form = await updateLinea(ln);                    
                }
            }

            globalThis.toast.success("Se han guardado las lineas asociadas ");
        } catch (error) {
            if (error.detail) {
                globalThis.toast.error(error.detail);
            } else {
                globalThis.toast.error(JSON.stringify(error));
            }
        } finally {
            loading = false;
        }
    }
</script>

<form action="" on:submit|preventDefault={onSave}>
    <Modal
        title={"Operador #" + (operador.id_operador || "Nuevo")}
        size="lg"
        classBody="mymodal"
        on:close={() => dispatch("close")}
    >
        <ul class="nav nav-tabs">
            <li class="nav-item">
                <a
                    class={"nav-link" + (tab === 0 ? " active" : "")}
                    href={"#"}
                    on:click|preventDefault={() => (tab = 0)}>Operador</a
                >
            </li>
            <li class={"nav-item" + (form.id_operador ? "" : " disabled")}>
                <a
                    class={"nav-link" + (tab === 1 ? " active" : "")}
                    href={"#"}
                    on:click|preventDefault={() => (tab = 1)}>Lineas</a
                >
            </li>
        </ul>

        <div class="p-3 bg-white">
            {#if tab === 0}
                <TabOperador {operador} bind:form={form} {escritura} />
            {/if}
            {#if tab === 1}
                <TabLineas {escritura} bind:lineas={lineas} />
            {/if}
        </div>

        <svelte:fragment slot="buttons">
            {#if escritura && tab === 0}
                <button class="btn btn-primary" type="submit" disabled={loading}
                    >Guardar</button
                >
                <button
                    class="btn btn-danger"
                    on:click|preventDefault={onDelete}
                    disabled={loading}>Eliminar</button
                >
            {/if}
            {#if escritura && tab === 1}
                <button
                    class="btn btn-primary"
                    type="button"
                    on:click|preventDefault={onSaveLineas}
                    disabled={loading}>Guardar</button
                >
            {/if}
        </svelte:fragment>
    </Modal>
</form>

<style>
    .disabled {
        pointer-events: none !important;
    }
</style>
