<script>
    import Modal from "../../components/Modal.svelte";
    import { getOperador } from "$/services/operadores";
    import { getLinea, getLineas, updateLinea } from "$/services/lineas";
    import { createEventDispatcher } from "svelte";
    import TableResponsive from "$/components/TableResponsive.svelte";
    const dispatch = createEventDispatcher();

    export let operador = {};
    export let escritura = false;

    let form = {}
    let loading = false;
    let lineas=[];
    let lineasNull=[];
    
    //console.log({ operador })
    $: begin(operador.id_operador )
 
    async function begin(id) {
        try {
            
            if (!id) return;
            form = await getOperador(id) || {}
            
        } catch (error) {
            globalThis.toast.success(error.detail || error)
        }
    }

    getLineas()
        .then(data => {
        lineas = data.filter(linea => 
            linea.id_operador === operador.id_operador || linea.id_operador === null
        );
        lineas = lineas.map(linea => ({
                        ...linea,
                        activo: linea.id_operador !== null,  
                        modificado: false ,
            }));        
         // Ordenar las líneas por route_long_name
         lineas = lineas.sort((a, b) => {
            if (a.route_long_name < b.route_long_name) return -1;
            if (a.route_long_name > b.route_long_name) return 1;
            return 0;
        });

    })
    .catch(error => globalThis.toast.error(error));


     

    function toggleCheckbox(linea, event) {
    const newState = event.target.checked;    
    linea.activo = newState;
    linea.modificado = true; 
    lineas = lineas; // Asignar el array a sí mismo para asegurar la reactividad en Svelte
    //console.log({ linea })
    return
  }

 
  async function onSave() {
    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'.
                        }));
 
        try {
            loading = true;
            if (operador.id_operador) 
            {
             
                    for (let ln of lineasModificadas) 
                    {
                        //console.log({ ln })
                        form = await updateLinea(ln)
                    }
                      
            }
            globalThis.toast.success('Se han guardado las lineas asociadas ')
            dispatch('refresh')
            dispatch('close')
        } catch (error) {
            if (error.detail) {
                globalThis.toast.success(error.detail)
            } else {
                globalThis.toast.success(JSON.stringify(error))
            }
        } finally {
            loading = false;
        }
    }
  


</script>

<form action="" on:submit|preventDefault={onSave}> 
    <Modal title={'Lineas Asociadas a ' + (operador.nombre_operador )}
        size="lg"
        on:close={() => dispatch('close')} >

        <div class={"form" + (escritura ? '' : ' disabled')}>
            <TableResponsive>
                <thead>
                    <tr>
                        <th>Linea</th>
                        <th>Asociada</th>                        
                    </tr>
                </thead>
            <tbody>
                {#each lineas as linea}
                <tr>
                        <td>{linea.route_long_name}</td>
                    <td>
                        <div class="form-check form-switch">
                        <input
                            class="form-check-input"
                            type="checkbox"
                            role="switch"
                            bind:checked = {linea.activo}  
                            on:change={(event) => toggleCheckbox(linea, event)}
                            id={`check-linea-${linea.id_linea}`}>
                            <label class="form-check-label" for={`check-linea-${linea.id_linea}`}>&nbsp;</label>
                        
                    </div>
                    </td>
                </tr>
                {/each}
            </tbody>
        </TableResponsive>
        </div>

        <svelte:fragment slot="buttons">
            {#if escritura}
                <button class="btn btn-primary" type="submit" disabled={loading}>Guardar</button>              
            {/if}
        </svelte:fragment>
    </Modal>
</form>

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