/* 
* Copyright 2016 Agencia Estatal de Administración Tibutaria
*
* Licencia con arreglo a la EUPL, Versión 1.1 o –en cuanto
* sean aprobadas por la Comisión Europea– versiones
* posteriores de la EUPL (la «Licencia»);
* Solo podrá usarse esta obra si se respeta la Licencia.
* Puede obtenerse una copia de la Licencia en:
*  
* https://joinup.ec.europa.eu/software/page/eupl
*  
* Salvo cuando lo exija la legislación aplicable o se acuerde
* por escrito, el programa distribuido con arreglo a la
* Licencia se distribuye «TAL CUAL», SIN GARANTÍAS NI CONDICIONES
* DE NINGÚN TIPO, ni expresasni implícitas.
*
* Véase la Licencia en el idioma concreto que rige los permisos y 
* limitaciones que establece la Licencia.
*/ 


package administrador;

import administrador.datos.*;
import administrador.utiles.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.grid.*;
import javax.swing.table.*;

public final class FormGestionCitas extends javax.swing.JFrame implements ListSelectionListener {

    PanelServidor panel;
    TablaHuecos tablaHuecos = new TablaHuecos();
    String cola;
    String turno;
    TModelGrid modeloGrid;
    GeneradorDataModel modeloGenerador;
    RegGenerador regGeneradorActual = null;
    boolean gridGeneradorCargado = false;
    boolean estamosVolcando = false;
    RangosDataModel modeloRangos;
    RegRango regRango = null;

    public FormGestionCitas(PanelServidor miPanel) {
        panel = miPanel;
        initComponents();
        cargarDatos();
        actualizarRangosenHuecos();
        setLocationRelativeTo(miPanel);
        btConfirmarCambios.setVisible(false);
        btCancelarEdicion.setVisible(false);
        modeloRangos = new RangosDataModel();
        modeloRangos.cargar(panel.getcadenaRangoHuecos());
        this.jTable1.setModel(modeloRangos);
        this.btConfirRangos.setEnabled(false);
        gridGeneracion.getParent().addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                gridGeneracionMouseReleased(evt);
            }
        });
    }

    public void actualizarRangosenHuecos() {
        tablaHuecos.actualualizaRangoHuecos(panel.getcadenaRangoHuecos());
    }

    void reiniciarRangos() {
        modeloRangos.cargar(panel.getcadenaRangoHuecos());
        this.jTable1.setModel(modeloRangos);
        jTable1.revalidate();
        jTable1.repaint();
    }

    void enviarRangosAlServidor() {
        String nuevoR = modeloRangos.generarNuevacadenaRangos();
        panel.comu.enviar(Comunicaciones.COD_ENVIO_MODI_RANGO, nuevoR);
        this.btConfirRangos.setEnabled(false);
    }

    void cargarDatos() {
        comboTurno1.addItem("M");
        comboTurno1.addItem("T");
        comboTurno2.addItem("M");
        comboTurno2.addItem("T");
        for (Iterator it = panel.getColeccionColas().iteradorValores(); it.hasNext();) {
            RegistroCola reg = (RegistroCola) it.next();
            if (reg.esCitaPrevia()) {
                comboColas1.addItem(reg.getId().trim() + " " + reg.getDescripcion().trim());
                comboColas2.addItem(reg.getId() + " " + reg.getDescripcion());
                comboColasOrigen.addItem(reg.getId().trim() + " " + reg.getDescripcion().trim());
                comboColasDestino.addItem(reg.getId().trim() + " " + reg.getDescripcion().trim());
            }
        }
        ponerHoraInicioPotable();
        modeloGrid = new TModelGrid();
        grid.setModel(modeloGrid);
        grid.getColumnModel().getColumn(2).setCellRenderer(new renderCeldaRoja());
        grid.addCeldaPulsadaListener((CeldaPulsadaEvent e) -> {
            incrementarOcupado(e.getFila());
        });
        grid.getSelectionModel().addListSelectionListener(this);
        grid.ponColumnaFija(3);
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        int[] seleccionadas = grid.getSelectedRows();
        if (seleccionadas.length > 1) {
            lbTotalCitas.setText("Citas en la selección: " + tablaHuecos.disponibles(seleccionadas));
        } else {
            lbTotalCitas.setText("Citas disponibles: " + tablaHuecos.disponibles());
        }
    }

    public void ponerHoraInicioPotable() {
        ponerHoraInicioPotable(null);
    }

    public void ponerHoraInicioPotable(java.util.Date dt) {
        GregorianCalendar cal = new GregorianCalendar();
        if (dt == null) {
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
        } else {
            cal.setTime(dt);
        }
        int mins = cal.get(Calendar.MINUTE);
        mins = ((mins / 5) + 1) * 5;
        cal.set(Calendar.MINUTE, mins);
        edHoraInicio.setValue(cal.getTime());
    }

    void incrementarOcupado(int fila) {
        TablaHuecos.Registro reg = tablaHuecos.datos.get(fila);
        if (reg.porOcupar < reg.numero) {
            reg.porOcupar++;
        } else {
            reg.porOcupar = 0;
        }
        refrescarGrid();
    }

    void marcarSeleccionOcupada() {
        int[] seleccionados = grid.getSelectedRows();
        tablaHuecos.ocupar(seleccionados);
        refrescarGrid();
    }

    public void incorporarCitas(String cola, String turno, String mapa) {
        grid.getSelectionModel().clearSelection();

        if (this.cola.equals(cola) && this.turno.equals(turno)) {
            if (mapa.equals("sin huecos")) {
                JOptionPane.showMessageDialog(this, "No hay citas disponibles para la cola y turno especificado");
                tablaHuecos.vaciar();
                lbTotalCitas.setText("");
            } else {
                tablaHuecos.incorporarCitas(mapa);
                lbTotalCitas.setText("Citas disponibles: " + tablaHuecos.disponibles());
            }
            refrescarGrid();
        }
    }

    void pedirDatos() {

        cola = ((String) comboColas1.getSelectedItem()).substring(0, 2);
        cola = cola.trim();
        turno = (String) comboTurno1.getSelectedItem();
        panel.comu.enviar(Comunicaciones.COD_SOLICITO_HUECOS_COLA, cola, turno);
        ponerPresentes();

    }

    void enviarOcupados() {
        if (JOptionPane.showConfirmDialog(this, "¿ Seguro que quiere eliminar los huecos seleccionados ? ", "CONFIRMACIÓN",
                JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
            return;
        }
        for (TablaHuecos.Registro reg : tablaHuecos.datos) {
            if (reg.porOcupar > 0) {
                panel.comu.enviar(Comunicaciones.COD_OCUPAR_HUECOS,
                        cola, reg.horaCita.toString(), String.valueOf(reg.porOcupar));
            }
        }
        if (cola != null) {
            panel.comu.enviar(Comunicaciones.COD_SOLICITO_HUECOS_COLA, cola, turno);
        }
    }

    void refrescarGrid() {
        grid.revalidate();
        grid.repaint();
    }

    void refrescarGridGeneracion() {
        gridGeneracion.revalidate();
        gridGeneracion.repaint();
    }

    void generarCitas() {
        RegGenerador r = validarCitasPropuestas();
        if (r != null && confirmarYEnviar(r)) {
            sincronizarPanelSuperior();
        }
    }

    RegGenerador validarCitasPropuestas() {
        try {
            java.util.Date d1 = (java.util.Date) edHoraInicio.getValue();
            java.util.Date d2 = (java.util.Date) edHoraFin.getValue();
            if (d1 == null) {
                msjBox("Debe especificar la hora inicial");
                edHoraInicio.requestFocus();
                return null;
            }
            if (d2 == null) {
                msjBox("Debe especificar la hora final");
                edHoraFin.requestFocus();
                return null;
            }
            GregorianCalendar cal1 = new GregorianCalendar();
            GregorianCalendar cal2 = new GregorianCalendar();
            cal2.setTime(d2);
            cal2.set(Calendar.YEAR, cal1.get(Calendar.YEAR));
            cal2.set(Calendar.MONTH, cal1.get(Calendar.MONTH));
            cal2.set(Calendar.DAY_OF_MONTH, cal1.get(Calendar.DAY_OF_MONTH));
            cal1.setTime(d1);
            cal1.set(Calendar.YEAR, cal2.get(Calendar.YEAR));
            cal1.set(Calendar.MONTH, cal2.get(Calendar.MONTH));
            cal1.set(Calendar.DAY_OF_MONTH, cal2.get(Calendar.DAY_OF_MONTH));
            Timestamp t1 = new Timestamp(cal1.getTimeInMillis());
            Timestamp t2 = new Timestamp(cal2.getTimeInMillis());
            if (t2.before(t1)) {
                msjBox("La hora final debe ser posterior a la inicial");
                edHoraFin.requestFocus();
                return null;
            }
            Long l = (Long) edDuracion.getValue();
            if (l == null) {
                msjBox("Debe especificar la duración de cada cita");
                edDuracion.requestFocus();
                return null;
            }
            int duracion = l.intValue();
            l = (Long) edNumPuestos.getValue();
            if (l == null || l.intValue() == 0) {
                msjBox("Debe especificar el número de puestos");
                edNumPuestos.requestFocus();
                return null;
            }
            int puestos = l.intValue();
            String colaSelec = (String) comboColas2.getSelectedItem();
            String[] colaPart = Global.split(colaSelec, ' ');
            RegGenerador r = new RegGenerador();
            r.cola = colaPart[0];
            r.descripcion = colaPart[1];
            r.turno = (String) comboTurno2.getSelectedItem();
            r.hInicio = t1;
            r.hFin = t2;
            r.duracion = duracion;
            r.puestos = puestos;
            return r;
        } catch (Exception exc) {
            msjBox("Error en entrada de datos");
        }
        return null;
    }

    void sincronizarPanelSuperior() {
        comboColas1.setSelectedItem(comboColas2.getSelectedItem());
        comboTurno1.setSelectedItem(comboTurno2.getSelectedItem());
        pedirDatos();
    }

    boolean confirmarYEnviar(RegGenerador r) {
        int lapso = (int) ((r.hFin.getTime() - r.hInicio.getTime()) / 60000l);
        int numHuecos = lapso / r.duracion;
        int numCitas = numHuecos * r.puestos;

        String inicio = Fecha.formatoHoraHM(r.hInicio);
        String fin = Fecha.formatoHoraHM(r.hFin);
        String texto = "<html>¿ Desea " + (numCitas > 0 ? ("crear  " + numCitas) : ("ocupar  " + (-numCitas))) + "  citas para la cola<br>- "
                + r.cola + " " + r.descripcion
                + " -<br> entre las " + inicio + " y las " + fin + "?</html>";
        if (JOptionPane.showConfirmDialog(this, texto, "CONFIRMACIÓN", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
            String mensaje = r.cola + "|" + r.turno + "|"
                    + r.hInicio.toString() + "|" + r.hFin.toString() + "|" + r.duracion + "|" + r.puestos;
            panel.comu.enviar(Comunicaciones.COD_GENERAR_HUECOS, mensaje);
            return true;
        }
        return false;
    }

    void descargarDatosGenerador() {
        String maquina = panel.servidorSql;
        BaseDeDatos bd = new BaseDeDatos();
        bd.estableceConexion(maquina);
        ResultSet rs = bd.dameLista("SELECT * FROM GeneradorCitas");
        modeloGenerador = new GeneradorDataModel();
        modeloGenerador.cargar(rs);
        gridGeneracion.setModel(modeloGenerador);
        gridGeneracion.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    void volcarDatosSql() {
        String Maquina = panel.servidorSql;
        BaseDeDatos bd = new BaseDeDatos();
        try {
            Connection con = bd.estableceConexion(Maquina);
            bd.SQL("DELETE FROM GeneradorCitas");
            String sql = "INSERT INTO GeneradorCitas (cola,turno,horaInicio,horaFin,duracion,puestos,ultimaEjecucion) values (?,?,?,?,?,?,?)";
            PreparedStatement st = con.prepareStatement(sql);
            for (int i = 0; i < modeloGenerador.getRowCount(); i++) {
                RegGenerador r = modeloGenerador.buscar(i);
                if (r.hInicio == null) { // el ultimo registro está vacio si estamos añadiendo
                    break;
                }
                st.setString(1, r.cola);
                st.setString(2, r.turno);
                st.setTimestamp(3, r.hInicio);
                st.setTimestamp(4, r.hFin);
                st.setInt(5, r.duracion);
                st.setInt(6, r.puestos);
                st.setTimestamp(7, r.ultimaEjecucion);
                st.execute();
            }
            bd.cierraConexion();
            JOptionPane.showMessageDialog(this, "Modificacion realizada");
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }

    void cambiadoPanel() {
        JPanel actual = (JPanel) panelTabs.getSelectedComponent();
        if (actual == panelTabConsulta) {
            btGenerar.setText("Generar Citas");
            btConfirmarCambios.setVisible(false);
            estamosVolcando = false;
            panelInferior.setVisible(true);
        }
        if (actual == panelGeneracionDiaria) {
            if (!gridGeneradorCargado) {
                descargarDatosGenerador();
                gridGeneradorCargado = true;
                panelInferior.setVisible(true);
            }
            btGenerar.setText("Volcar datos al Servidor");
            btConfirmarCambios.setVisible(true);
            estamosVolcando = true;
        }
        if (actual == panelRangos) {
            panelInferior.setVisible(false);
        }
    }

    void eliminarGenerador() {
        int fila = gridGeneracion.getSelectedRow();
        if (fila >= 0) {
            modeloGenerador.borrar(fila);
            refrescarGridGeneracion();
        }
        gridGeneracion.clearSelection();
    }

    void eliminarRango() {
        int fila = jTable1.getSelectedRow();
        if (fila >= 0) {
            modeloRangos.borrar(fila);
            jTable1.revalidate();
            jTable1.repaint();
            jTable1.clearSelection();
        }
    }

    void nuevoGenerador() {
        if (btCancelarEdicion.isVisible()) {
            return;
        }
        regGeneradorActual = modeloGenerador.nuevo();
        cargarGeneradorEnEditor(regGeneradorActual);
        int ultimaFila = modeloGenerador.getRowCount() - 1;
        gridGeneracion.setRowSelectionInterval(ultimaFila, ultimaFila);
        refrescarGridGeneracion();
        btCancelarEdicion.setVisible(true);
    }

    void editarGenerador() {
        int fila = gridGeneracion.getSelectedRow();
        if (fila >= 0) {
            regGeneradorActual = modeloGenerador.buscar(fila);
            cargarGeneradorEnEditor(regGeneradorActual);
        }
    }

    void vaciarEditores() {
        RegGenerador vacio = new RegGenerador();
        cargarGeneradorEnEditor(vacio);
    }

    void cancelarEdicion() {
        eliminarGenerador();
        btCancelarEdicion.setVisible(false);
    }

    void cargarGeneradorEnEditor(RegGenerador r) {
        if (r.cola != null) {
            String sCola = r.cola + " ";
            for (int i = 0; i < comboColas2.getItemCount(); i++) {
                String s = (String) comboColas2.getItemAt(i);
                if (s.startsWith(sCola)) {
                    this.comboColas2.setSelectedIndex(i);
                    break;
                }
            }
        }
        if (r.turno != null) {
            this.comboTurno2.setSelectedItem(r.turno);
        }
        this.edHoraInicio.setValue(r.hInicio);
        this.edHoraFin.setValue(r.hFin);
        this.edDuracion.setValue((long) r.duracion);
        this.edNumPuestos.setValue((long) r.puestos);
    }

    void confirmarCambiosGenerador() {
        RegGenerador r = validarCitasPropuestas();
        if (r == null) {
            return;
        }
        if (regGeneradorActual == null) {
            RegGenerador rg;
            for (int i = 0; i < modeloGenerador.getRowCount(); i++) {
                rg = modeloGenerador.buscar(i);
                if (rg.cola.equals(r.cola)) {
                    regGeneradorActual = rg;
                }
            }
            if (regGeneradorActual == null) {
                modeloGenerador.nuevo(r);
                regGeneradorActual = r;
            }
        }
        regGeneradorActual.cola = r.cola;
        regGeneradorActual.turno = r.turno;
        regGeneradorActual.hInicio = r.hInicio;
        regGeneradorActual.hFin = r.hFin;
        regGeneradorActual.duracion = r.duracion;
        regGeneradorActual.puestos = r.puestos;
        refrescarGridGeneracion();
        regGeneradorActual = null;
        vaciarEditores();
        btCancelarEdicion.setVisible(false);
    }

    void ajustarPopupGenerador() {
        boolean activar = gridGeneracion.getSelectedRow() >= 0;
        menuGenEditar.setEnabled(activar);
        menuGenEliminar.setEnabled(activar);

    }

    void msjBox(String s) {
        JOptionPane.showMessageDialog(this, s);
    }

    void ponerFechaMinima() {
        String colaSelec = (String) comboColas2.getSelectedItem();
        String[] colaPart = Global.split(colaSelec, ' ');
        java.util.Date dt = panel.pedirHoraValida(colaPart[0]);
        if (dt == null) {
            return;
        }
        java.util.Date dh = new java.util.Date();

        if (dt.before(dh)) {
            dt = dh;
        }
        ponerHoraInicioPotable(dt);

    }

    void ponerRangoenetiqueta2() {
        String colaSelec = (String) comboColas2.getSelectedItem();
        String[] colaPart = Global.split(colaSelec, ' ');
        lbRango1.setText("");
        String colaR = tablaHuecos.buscarRangoHuecos2(colaPart[0]);
        if (!colaR.equalsIgnoreCase(" ")) {
            String nombrelargo = nombreDeCola(colaR);
            lbRango1.setText("Cola en el rango " + nombrelargo);

        }
    }

    void ponerPresentes() {
        String colaSelec = (String) comboColas1.getSelectedItem();
        String[] colaPart = Global.split(colaSelec, ' ');
        String pres1 = panel.pedirPresentes(colaPart[0]);
        lbPresentesCola.setText("Presentes " + pres1);
        lbRango.setText("");
        String colaR = tablaHuecos.buscarRangoHuecos2(colaPart[0]);
        if (!colaR.equalsIgnoreCase(" ")) {
            String nombrelargo = nombreDeCola(colaR);
            lbRango.setText("Cola en el rango " + nombrelargo);

        }
    }

    String nombreDeCola(String colaH) {
        for (Iterator it = panel.getColeccionColas().iteradorValores(); it.hasNext();) {
            RegistroCola reg = (RegistroCola) it.next();
            if (reg.getCodigo().equalsIgnoreCase(colaH)) {
                return reg.getCodigo().trim() + " " + reg.getDescripcion().trim();
            }
        }
        return "No encontrado";
    }

    void adicionarColaHuecos() {
        String colaO = ((String) comboColasOrigen.getSelectedItem()).substring(0, 2);
        String colaD = ((String) comboColasDestino.getSelectedItem()).substring(0, 2);
        colaO = colaO.trim();
        colaD = colaD.trim();
        if (modeloRangos.existeCola(colaO)) {
            modeloRangos.modificaColaDestino(colaO, colaD);
        } else {
            modeloRangos.addCola(colaO, colaD);
        }
        jTable1.revalidate();
        jTable1.repaint();

    }

    void sincronizarOrigenDestino() {
        int pos = this.jTable1.getSelectedRow();
        if (pos == -1) {
            return;
        }
        String origen = this.jTable1.getValueAt(pos, 0).toString();
        String destino = this.jTable1.getValueAt(pos, 1).toString();

        this.comboColasOrigen.setSelectedItem(origen);
        this.comboColasDestino.setSelectedItem(destino);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
   // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   private void initComponents() {

      jTextField2 = new javax.swing.JTextField();
      popupMenuGrid = new javax.swing.JPopupMenu();
      jMenuItem1 = new javax.swing.JMenuItem();
      popupMenuGenerador = new javax.swing.JPopupMenu();
      menuGenEliminar = new javax.swing.JMenuItem();
      menuGenEditar = new javax.swing.JMenuItem();
      menuGenNuevo = new javax.swing.JMenuItem();
      PopupRangos = new javax.swing.JPopupMenu();
      menuRangoEliminar = new javax.swing.JMenuItem();
      panelInferior = new javax.swing.JPanel();
      comboColas2 = new javax.swing.JComboBox();
      comboTurno2 = new javax.swing.JComboBox();
      jLabel1 = new javax.swing.JLabel();
      jLabel2 = new javax.swing.JLabel();
      jLabel3 = new javax.swing.JLabel();
      jLabel4 = new javax.swing.JLabel();
      jLabel5 = new javax.swing.JLabel();
      jLabel6 = new javax.swing.JLabel();
      edHoraInicio = new JFormattedTextField(new SimpleDateFormat("HH:mm"));
      edHoraFin = new JFormattedTextField(new SimpleDateFormat("HH:mm"));
      edDuracion = new JFormattedTextField(new DecimalFormat("##"));
      edNumPuestos = new JFormattedTextField(new DecimalFormat("##"));
      jPanel3 = new javax.swing.JPanel();
      btCancelarEdicion = new javax.swing.JButton();
      btConfirmarCambios = new javax.swing.JButton();
      btGenerar = new javax.swing.JButton();
      lbRango1 = new javax.swing.JLabel();
      panelTabs = new javax.swing.JTabbedPane();
      panelTabConsulta = new javax.swing.JPanel();
      jPanel2 = new javax.swing.JPanel();
      comboTurno1 = new javax.swing.JComboBox();
      jLabel7 = new javax.swing.JLabel();
      comboColas1 = new javax.swing.JComboBox();
      btEnviarOcupados = new javax.swing.JButton();
      jButton1 = new javax.swing.JButton();
      lbTotalCitas = new javax.swing.JLabel();
      lbPresentesCola = new javax.swing.JLabel();
      lbRango = new javax.swing.JLabel();
      jPanel1 = new javax.swing.JPanel();
      jScrollPane1 = new javax.swing.JScrollPane();
      grid = new javax.swing.grid.JGrid();
      panelGeneracionDiaria = new javax.swing.JPanel();
      jScrollPane2 = new javax.swing.JScrollPane();
      gridGeneracion = new javax.swing.JTable();
      panelRangos = new javax.swing.JPanel();
      jScrollPane3 = new javax.swing.JScrollPane();
      jTable1 = new javax.swing.JTable();
      comboColasOrigen = new javax.swing.JComboBox();
      comboColasDestino = new javax.swing.JComboBox();
      btConfirRangos = new javax.swing.JButton();
      butonAbajo = new javax.swing.JButton();
      butonReiniciar = new javax.swing.JButton();

      jTextField2.setText("jTextField2"); // NOI18N

      jMenuItem1.setText("Marcar seleccion como ocupado"); // NOI18N
      jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            jMenuItem1ActionPerformed(evt);
         }
      });
      popupMenuGrid.add(jMenuItem1);

      popupMenuGenerador.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
         public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
         }
         public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
         }
         public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            popupMenuGeneradorPopupMenuWillBecomeVisible(evt);
         }
      });

      menuGenEliminar.setText("Eliminar seleccionado"); // NOI18N
      menuGenEliminar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuGenEliminarActionPerformed(evt);
         }
      });
      popupMenuGenerador.add(menuGenEliminar);

      menuGenEditar.setText("Editar seleccionado"); // NOI18N
      menuGenEditar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuGenEditarActionPerformed(evt);
         }
      });
      popupMenuGenerador.add(menuGenEditar);

      menuGenNuevo.setText("Añadir uno nuevo"); // NOI18N
      menuGenNuevo.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuGenNuevoActionPerformed(evt);
         }
      });
      popupMenuGenerador.add(menuGenNuevo);

      menuRangoEliminar.setLabel("Eliminar");
      menuRangoEliminar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuRangoEliminarActionPerformed(evt);
         }
      });
      PopupRangos.add(menuRangoEliminar);

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle("Gestión de huecos en CITA PREVIA"); // NOI18N
      addWindowListener(new java.awt.event.WindowAdapter() {
         public void windowClosing(java.awt.event.WindowEvent evt) {
            formWindowClosing(evt);
         }
      });

      panelInferior.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

      comboColas2.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboColas2ActionPerformed(evt);
         }
      });

      jLabel1.setText("Cola"); // NOI18N

      jLabel2.setText("Turno"); // NOI18N

      jLabel3.setText("Hora Inicio"); // NOI18N

      jLabel4.setText("Hora Fin"); // NOI18N

      jLabel5.setText("<html>Numero <br>Puestos</html>"); // NOI18N

      jLabel6.setText("<html>Duración<BR> (minutos)</html>"); // NOI18N

      edHoraInicio.addKeyListener(new java.awt.event.KeyAdapter() {
         public void keyTyped(java.awt.event.KeyEvent evt) {
            HoraKeyTyped(evt);
         }
      });

      edHoraFin.addKeyListener(new java.awt.event.KeyAdapter() {
         public void keyTyped(java.awt.event.KeyEvent evt) {
            HoraKeyTyped(evt);
         }
      });

      btCancelarEdicion.setText("Cancelar edición"); // NOI18N
      btCancelarEdicion.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btCancelarEdicionActionPerformed(evt);
         }
      });

      btConfirmarCambios.setText("Confirmar cambios"); // NOI18N
      btConfirmarCambios.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btConfirmarCambiosActionPerformed(evt);
         }
      });

      btGenerar.setText("Generar citas"); // NOI18N
      btGenerar.setMargin(new java.awt.Insets(2, 10, 2, 10));
      btGenerar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btGenerarActionPerformed(evt);
         }
      });

      org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
      jPanel3.setLayout(jPanel3Layout);
      jPanel3Layout.setHorizontalGroup(
         jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .add(btConfirmarCambios, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 150, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(btCancelarEdicion, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 150, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 80, Short.MAX_VALUE)
            .add(btGenerar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 291, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
      );
      jPanel3Layout.setVerticalGroup(
         jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
            .add(btConfirmarCambios, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(btCancelarEdicion, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(btGenerar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
      );

      lbRango1.setForeground(new java.awt.Color(255, 51, 51));
      lbRango1.setText("jLabel8");

      org.jdesktop.layout.GroupLayout panelInferiorLayout = new org.jdesktop.layout.GroupLayout(panelInferior);
      panelInferior.setLayout(panelInferiorLayout);
      panelInferiorLayout.setHorizontalGroup(
         panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
         .add(panelInferiorLayout.createSequentialGroup()
            .addContainerGap()
            .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(panelInferiorLayout.createSequentialGroup()
                  .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(comboColas2, 0, 349, Short.MAX_VALUE)
                     .add(jLabel1))
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(comboTurno2, 0, 63, Short.MAX_VALUE)
                     .add(jLabel2))
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(edHoraInicio)
                     .add(jLabel3))
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                     .add(edHoraFin, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE)
                     .add(jLabel4)))
               .add(panelInferiorLayout.createSequentialGroup()
                  .add(lbRango1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 420, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .add(0, 0, Short.MAX_VALUE)))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(edDuracion)
               .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(edNumPuestos, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
               .add(jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
            .add(13, 13, 13))
      );
      panelInferiorLayout.setVerticalGroup(
         panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelInferiorLayout.createSequentialGroup()
            .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
               .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                  .add(jLabel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
               .add(panelInferiorLayout.createSequentialGroup()
                  .add(lbRango1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                     .add(jLabel4)
                     .add(jLabel3)
                     .add(jLabel2)
                     .add(jLabel1))))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(panelInferiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(comboColas2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(comboTurno2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(edHoraInicio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(edHoraFin, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(edDuracion, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(edNumPuestos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(9, 9, 9)
            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );

      getContentPane().add(panelInferior, java.awt.BorderLayout.SOUTH);

      panelTabs.setName("consulta"); // NOI18N
      panelTabs.addChangeListener(new javax.swing.event.ChangeListener() {
         public void stateChanged(javax.swing.event.ChangeEvent evt) {
            panelTabsStateChanged(evt);
         }
      });

      panelTabConsulta.setLayout(new java.awt.BorderLayout());

      jPanel2.setMinimumSize(new java.awt.Dimension(0, 100));
      jPanel2.setPreferredSize(new java.awt.Dimension(0, 80));

      jLabel7.setText("Seleccione Cola y Turno a mostrar"); // NOI18N

      comboColas1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboColas1ActionPerformed(evt);
         }
      });

      btEnviarOcupados.setText("Preguntar Huecos"); // NOI18N
      btEnviarOcupados.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btEnviarOcupadosActionPerformed(evt);
         }
      });

      jButton1.setText("Ocupar Huecos"); // NOI18N
      jButton1.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
         }
      });

      lbPresentesCola.setText("jLabel8");

      lbRango.setForeground(new java.awt.Color(255, 51, 51));
      lbRango.setText("jLabel8");

      org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
      jPanel2.setLayout(jPanel2Layout);
      jPanel2Layout.setHorizontalGroup(
         jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(jPanel2Layout.createSequentialGroup()
                  .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                     .add(org.jdesktop.layout.GroupLayout.LEADING, comboColas1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 290, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                     .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel7))
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(comboTurno1, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .add(14, 14, 14)
                  .add(btEnviarOcupados, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .add(18, 18, 18)
                  .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 150, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
               .add(jPanel2Layout.createSequentialGroup()
                  .add(lbPresentesCola, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 208, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                  .add(lbRango, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 322, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                  .add(lbTotalCitas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
      );
      jPanel2Layout.setVerticalGroup(
         jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(jPanel2Layout.createSequentialGroup()
            .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
               .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
                  .add(5, 5, 5)
                  .add(jLabel7)
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                     .add(comboColas1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                     .add(comboTurno1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
               .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
                  .addContainerGap()
                  .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                     .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                     .add(btEnviarOcupados, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .add(12, 12, 12)
            .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                  .add(lbPresentesCola)
                  .add(lbRango))
               .add(org.jdesktop.layout.GroupLayout.TRAILING, lbTotalCitas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(29, Short.MAX_VALUE))
      );

      panelTabConsulta.add(jPanel2, java.awt.BorderLayout.NORTH);

      jPanel1.setLayout(new java.awt.BorderLayout());

      grid.setModel(new javax.swing.table.DefaultTableModel(
         new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
         },
         new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
         }
      ));
      grid.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mouseReleased(java.awt.event.MouseEvent evt) {
            gridMouseReleased(evt);
         }
      });
      jScrollPane1.setViewportView(grid);

      jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

      panelTabConsulta.add(jPanel1, java.awt.BorderLayout.CENTER);

      panelTabs.addTab("Consulta HOY", panelTabConsulta);

      panelGeneracionDiaria.setName("diario"); // NOI18N

      gridGeneracion.setModel(new javax.swing.table.DefaultTableModel(
         new Object [][] {
            {null}
         },
         new String [] {
            "Title 1"
         }
      ));
      gridGeneracion.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mouseClicked(java.awt.event.MouseEvent evt) {
            gridGeneracionMouseClicked(evt);
         }
         public void mouseReleased(java.awt.event.MouseEvent evt) {
            gridGeneracionMouseReleased(evt);
         }
      });
      jScrollPane2.setViewportView(gridGeneracion);

      org.jdesktop.layout.GroupLayout panelGeneracionDiariaLayout = new org.jdesktop.layout.GroupLayout(panelGeneracionDiaria);
      panelGeneracionDiaria.setLayout(panelGeneracionDiariaLayout);
      panelGeneracionDiariaLayout.setHorizontalGroup(
         panelGeneracionDiariaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelGeneracionDiariaLayout.createSequentialGroup()
            .addContainerGap()
            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 676, Short.MAX_VALUE)
            .addContainerGap())
      );
      panelGeneracionDiariaLayout.setVerticalGroup(
         panelGeneracionDiariaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelGeneracionDiariaLayout.createSequentialGroup()
            .addContainerGap()
            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
            .addContainerGap())
      );

      panelTabs.addTab("Generaci\u00f3n diaria", panelGeneracionDiaria);

      jTable1.setModel(new javax.swing.table.DefaultTableModel(
         new Object [][] {
            {},
            {},
            {},
            {}
         },
         new String [] {

         }
      ));
      jTable1.setComponentPopupMenu(PopupRangos);
      jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
      jTable1.setShowVerticalLines(false);
      jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
         public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTable1MouseClicked(evt);
         }
      });
      jScrollPane3.setViewportView(jTable1);

      comboColasOrigen.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboColasOrigenActionPerformed(evt);
         }
      });

      comboColasDestino.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            comboColasDestinoActionPerformed(evt);
         }
      });

      btConfirRangos.setText("Confirmar");
      btConfirRangos.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btConfirRangosActionPerformed(evt);
         }
      });

      butonAbajo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/abajo1.gif"))); // NOI18N
      butonAbajo.setText("Añadir");
      butonAbajo.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            butonAbajoActionPerformed(evt);
         }
      });

      butonReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/reiniciar.gif"))); // NOI18N
      butonReiniciar.setText("Reiniciar");
      butonReiniciar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            butonReiniciarActionPerformed(evt);
         }
      });

      org.jdesktop.layout.GroupLayout panelRangosLayout = new org.jdesktop.layout.GroupLayout(panelRangos);
      panelRangos.setLayout(panelRangosLayout);
      panelRangosLayout.setHorizontalGroup(
         panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(org.jdesktop.layout.GroupLayout.TRAILING, panelRangosLayout.createSequentialGroup()
            .add(panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(panelRangosLayout.createSequentialGroup()
                  .add(192, 192, 192)
                  .add(butonAbajo))
               .add(panelRangosLayout.createSequentialGroup()
                  .addContainerGap()
                  .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 482, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 56, Short.MAX_VALUE)
            .add(panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(panelRangosLayout.createSequentialGroup()
                  .add(butonReiniciar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 113, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .add(35, 35, 35))
               .add(org.jdesktop.layout.GroupLayout.TRAILING, panelRangosLayout.createSequentialGroup()
                  .add(btConfirRangos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 127, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                  .add(21, 21, 21))))
         .add(panelRangosLayout.createSequentialGroup()
            .addContainerGap()
            .add(comboColasOrigen, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 217, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(41, 41, 41)
            .add(comboColasDestino, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 217, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
      );
      panelRangosLayout.setVerticalGroup(
         panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelRangosLayout.createSequentialGroup()
            .add(30, 30, 30)
            .add(panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(comboColasOrigen, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(comboColasDestino, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(18, 18, 18)
            .add(panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(butonAbajo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(butonReiniciar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .add(panelRangosLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
               .add(panelRangosLayout.createSequentialGroup()
                  .add(74, 74, 74)
                  .add(btConfirRangos, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
               .add(panelRangosLayout.createSequentialGroup()
                  .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                  .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 335, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(65, Short.MAX_VALUE))
      );

      panelTabs.addTab("Rangos", panelRangos);

      getContentPane().add(panelTabs, java.awt.BorderLayout.CENTER);

      pack();
   }// </editor-fold>//GEN-END:initComponents
   private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
       panel.cerrarGestionCitas();
   }//GEN-LAST:event_formWindowClosing

   private void btGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGenerarActionPerformed
       if (estamosVolcando) {
           volcarDatosSql();
       } else {
           generarCitas();
       }
   }//GEN-LAST:event_btGenerarActionPerformed

   private void btEnviarOcupadosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEnviarOcupadosActionPerformed
       pedirDatos();
   }//GEN-LAST:event_btEnviarOcupadosActionPerformed

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       enviarOcupados();
   }//GEN-LAST:event_jButton1ActionPerformed

   private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
       marcarSeleccionOcupada();
   }//GEN-LAST:event_jMenuItem1ActionPerformed

   private void gridMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gridMouseReleased
       if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
           popupMenuGrid.show(grid, evt.getPoint().x, evt.getPoint().y);
       }
   }//GEN-LAST:event_gridMouseReleased

   private void panelTabsStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_panelTabsStateChanged
       cambiadoPanel();
   }//GEN-LAST:event_panelTabsStateChanged

   private void menuGenEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGenEliminarActionPerformed
       eliminarGenerador();
   }//GEN-LAST:event_menuGenEliminarActionPerformed

   private void gridGeneracionMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gridGeneracionMouseReleased
       if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
           popupMenuGenerador.show(gridGeneracion, evt.getPoint().x, evt.getPoint().y);
       }
   }//GEN-LAST:event_gridGeneracionMouseReleased

   private void menuGenNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGenNuevoActionPerformed
       nuevoGenerador();
   }//GEN-LAST:event_menuGenNuevoActionPerformed

   private void menuGenEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuGenEditarActionPerformed
       editarGenerador();
   }//GEN-LAST:event_menuGenEditarActionPerformed

   private void gridGeneracionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gridGeneracionMouseClicked
       if (evt.getClickCount() > 1) {
           editarGenerador();
       }
   }//GEN-LAST:event_gridGeneracionMouseClicked

   private void btConfirmarCambiosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirmarCambiosActionPerformed
       confirmarCambiosGenerador();
   }//GEN-LAST:event_btConfirmarCambiosActionPerformed

   private void btCancelarEdicionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarEdicionActionPerformed
       cancelarEdicion();
}//GEN-LAST:event_btCancelarEdicionActionPerformed

   private void HoraKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_HoraKeyTyped
       if (evt.getKeyChar() == '.' || evt.getKeyChar() == ' ') {
           evt.setKeyChar(':');
       }
   }//GEN-LAST:event_HoraKeyTyped

   private void popupMenuGeneradorPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_popupMenuGeneradorPopupMenuWillBecomeVisible
       ajustarPopupGenerador();
   }//GEN-LAST:event_popupMenuGeneradorPopupMenuWillBecomeVisible

private void comboColas2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboColas2ActionPerformed
    ponerFechaMinima();
    ponerRangoenetiqueta2();
}//GEN-LAST:event_comboColas2ActionPerformed

private void comboColas1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboColas1ActionPerformed
    ponerPresentes();
}//GEN-LAST:event_comboColas1ActionPerformed

    private void comboColasOrigenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboColasOrigenActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboColasOrigenActionPerformed

    private void comboColasDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboColasDestinoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboColasDestinoActionPerformed

    private void menuRangoEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuRangoEliminarActionPerformed
        eliminarRango();
        this.btConfirRangos.setEnabled(true);
    }//GEN-LAST:event_menuRangoEliminarActionPerformed

    private void butonAbajoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butonAbajoActionPerformed
        // TODO add your handling code here:
        adicionarColaHuecos();
        this.btConfirRangos.setEnabled(true);
    }//GEN-LAST:event_butonAbajoActionPerformed

    private void butonReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butonReiniciarActionPerformed
        // TODO add your handling code here:
        reiniciarRangos();
        this.btConfirRangos.setEnabled(false);
    }//GEN-LAST:event_butonReiniciarActionPerformed

    private void btConfirRangosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirRangosActionPerformed
        // TODO add your handling code here:
        enviarRangosAlServidor();
    }//GEN-LAST:event_btConfirRangosActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        sincronizarOrigenDestino();
    }//GEN-LAST:event_jTable1MouseClicked

   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JPopupMenu PopupRangos;
   private javax.swing.JButton btCancelarEdicion;
   private javax.swing.JButton btConfirRangos;
   private javax.swing.JButton btConfirmarCambios;
   private javax.swing.JButton btEnviarOcupados;
   private javax.swing.JButton btGenerar;
   private javax.swing.JButton butonAbajo;
   private javax.swing.JButton butonReiniciar;
   private javax.swing.JComboBox comboColas1;
   private javax.swing.JComboBox comboColas2;
   private javax.swing.JComboBox comboColasDestino;
   private javax.swing.JComboBox comboColasOrigen;
   private javax.swing.JComboBox comboTurno1;
   private javax.swing.JComboBox comboTurno2;
   private javax.swing.JFormattedTextField edDuracion;
   private javax.swing.JFormattedTextField edHoraFin;
   private javax.swing.JFormattedTextField edHoraInicio;
   private javax.swing.JFormattedTextField edNumPuestos;
   private javax.swing.grid.JGrid grid;
   private javax.swing.JTable gridGeneracion;
   private javax.swing.JButton jButton1;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JLabel jLabel3;
   private javax.swing.JLabel jLabel4;
   private javax.swing.JLabel jLabel5;
   private javax.swing.JLabel jLabel6;
   private javax.swing.JLabel jLabel7;
   private javax.swing.JMenuItem jMenuItem1;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JPanel jPanel2;
   private javax.swing.JPanel jPanel3;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JScrollPane jScrollPane2;
   private javax.swing.JScrollPane jScrollPane3;
   private javax.swing.JTable jTable1;
   private javax.swing.JTextField jTextField2;
   private javax.swing.JLabel lbPresentesCola;
   private javax.swing.JLabel lbRango;
   private javax.swing.JLabel lbRango1;
   private javax.swing.JLabel lbTotalCitas;
   private javax.swing.JMenuItem menuGenEditar;
   private javax.swing.JMenuItem menuGenEliminar;
   private javax.swing.JMenuItem menuGenNuevo;
   private javax.swing.JMenuItem menuRangoEliminar;
   private javax.swing.JPanel panelGeneracionDiaria;
   private javax.swing.JPanel panelInferior;
   private javax.swing.JPanel panelRangos;
   private javax.swing.JPanel panelTabConsulta;
   private javax.swing.JTabbedPane panelTabs;
   private javax.swing.JPopupMenu popupMenuGenerador;
   private javax.swing.JPopupMenu popupMenuGrid;
   // End of variables declaration//GEN-END:variables

    class TModelGrid extends AbstractTableModel {

        private final String[] titulos = {"Hora cita", "Disponibles", "Ocupar", ""};

        @Override
        public String getColumnName(int column) {
            return titulos[column];
        }

        @Override
        public int getColumnCount() {
            return 4;
        }

        @Override
        public int getRowCount() {
            return tablaHuecos.datos.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            TablaHuecos.Registro reg = tablaHuecos.datos.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return Fecha.formatoHoraHM(reg.horaCita);
                case 1:
                    return reg.numero;
                case 2:
                    return reg.porOcupar;
                case 3:
                    return "OCUPAR";
            }
            return "??";
        }
    }

    public class renderCeldaRoja extends javax.swing.table.DefaultTableCellRenderer {

        public renderCeldaRoja() {
            super();
        }

        @Override
        public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            try {
                if (value == null) {
                    return null;
                }
                int valor = ((Integer) value);
                setText(value.toString());
                setBackground(valor == 0 ? table.getBackground() : java.awt.Color.PINK);
                setForeground(table.getForeground());
                return this;
            } catch (Exception exc) {
                return null;
            }
        }
    }

    class RegGenerador {

        public String cola;
        public String descripcion;
        public String turno;
        public Timestamp hInicio;
        public Timestamp hFin;
        public int duracion;
        public int puestos;
        public Timestamp ultimaEjecucion;
    }

    class GeneradorDataModel extends AbstractTableModel {

        private final String[] titulos = {"COLA", "TURNO", "HORA INICIO", "HORA FIN", "DURACIÓN", "PUESTOS"};
        ArrayList<RegGenerador> data = new ArrayList<>(25);

        public void cargar(ResultSet rs) {
            try {
                while (rs.next()) {
                    RegGenerador r = new RegGenerador();
                    r.cola = rs.getString(1);
                    r.turno = rs.getString(2);
                    r.hInicio = rs.getTimestamp(3);
                    r.hFin = rs.getTimestamp(4);
                    r.duracion = rs.getInt(5);
                    r.puestos = rs.getInt(6);
                    r.ultimaEjecucion = rs.getTimestamp(7);
                    data.add(r);
                }
            } catch (Exception exc) {
                msjBox("ERROR al cargar los registros de la tabla GeneradorCitas\nNo se puede continuar");
                data.clear();
            }
        }

        @Override
        public int getColumnCount() {
            return 6;
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            RegGenerador r = data.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return r.cola;
                case 1:
                    return r.turno;
                case 2:
                    if (r.hInicio != null) {
                        return Fecha.formatoHoraHM(r.hInicio);
                    } else {
                        return "";
                    }
                case 3:
                    if (r.hFin != null) {
                        return Fecha.formatoHoraHM(r.hFin);
                    } else {
                        return "";
                    }
                case 4:
                    return r.duracion + "";
                case 5:
                    return r.puestos + "";
            }
            return "";
        }

        @Override
        public String getColumnName(int column) {
            return titulos[column];
        }

        public void borrar(int n) {
            data.remove(n);
        }

        public RegGenerador nuevo() {
            RegGenerador r = new RegGenerador();
            data.add(r);
            return r;
        }

        public void nuevo(RegGenerador r) {
            data.add(r);
        }

        public RegGenerador buscar(int fila) {
            return data.get(fila);
        }
    }

    class RegRango {

        public String colaOrigen;
        public String colaDestino;
        public String colaO;
        public String colaD;

    }

    class RangosDataModel extends AbstractTableModel {

        private final String[] titulos = {"COLA ORIGEN", "COLA DESTINO"};
        ArrayList<RegRango> data = new ArrayList<>(10);

        public void cargar(String listarango) {
            data.clear();
            String[] lineas = Global.split(listarango, '|');
            for (String linea : lineas) {
                String[] campos = Global.split(linea, '=');
                if (campos.length == 2) {
                    RegRango r = new RegRango();
                    r.colaO = campos[0];
                    r.colaD = campos[1];
                    r.colaOrigen = nombreDeCola(campos[0]);
                    r.colaDestino = nombreDeCola(campos[1]);
                    data.add(r);

                }
            }

        }

        public Object getValueAtLargo(int rowIndex, int columnIndex) {
            RegRango r = data.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return r.colaO;
                case 1:
                    return r.colaD;
            }
            return "";
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public String getColumnName(int column) {
            return titulos[column];
        }

        public void borrar(int n) {
            data.remove(n);
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            RegRango r = data.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return r.colaOrigen;
                case 1:
                    return r.colaDestino;
            }
            return "";
        }

        public boolean existeCola(String colaO) {
            for (RegRango r : data) {
                if (r.colaO.equalsIgnoreCase(colaO)) {
                    return true;
                }
            }
            return false;
        }

        public void modificaColaDestino(String colaO, String colaD) {
            for (RegRango r : data) {
                if (r.colaO.equalsIgnoreCase(colaO)) {
                    r.colaD = colaD;
                    r.colaDestino = nombreDeCola(colaD);
                    return;
                }
            }
        }

        public void addCola(String colaO, String colaD) {

            RegRango r = new RegRango();
            r.colaO = colaO;
            r.colaD = colaD;
            r.colaOrigen = nombreDeCola(colaO);
            r.colaDestino = nombreDeCola(colaD);
            data.add(r);

        }

        String generarNuevacadenaRangos() {
            StringBuilder sb = new StringBuilder("");
            for (RegRango r : data) {
                sb.append(r.colaO).append('=').append(r.colaD).append('|');
            }
            if (sb.length() > 0) {
                sb.setLength(sb.length() - 1);
            }
            return sb.toString();
        }

    }
}
