/* 
* 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 gestor;

import gestor.datos.*;
import gestor.utiles.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public final class DlgOfrecerCitas extends javax.swing.JDialog {

   PanelTactil padre;
   RegistroHuecos regSeleccionado = null;
   String rotulo;
   javax.swing.Timer timerCierraAviso;
   int tamañoHuecos = 0;
   boolean pulsadorAutomatico = false;
   int maxhuecos = 0;
   RegistroHuecos[] regs;
   int pos = 0;
   int grande = 0;

   public DlgOfrecerCitas(PanelTactil padre) {
      super(padre, true);
      this.padre = padre;
      initComponents();
      preparaTimerCerrar();
      this.setLocationRelativeTo(padre);
      grande = getWidth() + 350;
   }

   void preparaTimerCerrar() {
      timerCierraAviso = new javax.swing.Timer(Configuracion.instanciaUnica().segundosCierreVentanas * 1000, new java.awt.event.ActionListener() {

         public void actionPerformed(java.awt.event.ActionEvent evt) {
            pulsadoCancelar();
         }
      });
      timerCierraAviso.start();
   }

   void confirmarYTerminar(JButton boton) {
      RegistroHuecos reg = (RegistroHuecos) boton.getClientProperty("hueco");
      if (abortarSiNoDisponible(boton, reg)) {
         return;
      }
      DlgConfirmarTicket confirmacion = new DlgConfirmarTicket(this.padre);
      long minutosMargen = Configuracion.instanciaUnica().minutosTicketInmediato * 60000l;
      if (reg.horaCita.getTime() >= (System.currentTimeMillis() + minutosMargen)) {
         confirmacion.setPregunta(Global.trad.valor("ReservarHoraPara"));
      } else {
         confirmacion.setPregunta(Global.trad.valor("imprimirTicketPara"));
      }
      confirmacion.setRotulo(rotulo.toUpperCase());
      confirmacion.setRotuloHora(reg.horaCita);
      timerCierraAviso.stop();
      confirmacion.setVisible(true);
      timerCierraAviso.start();
      boolean confirmado = confirmacion.emitirTicket;
      confirmacion.dispose();
      confirmacion = null;
      Global.mainForm.resetMemoria();
      if (confirmado && !abortarSiNoDisponible(boton, reg)) {
         regSeleccionado = reg;
         setVisible(false);
      }
   }

   boolean abortarSiNoDisponible(JButton boton, RegistroHuecos reg) {
      if (!TablaHuecos.getTablaHuecos().sigueDisponible(reg.cola, reg.horaCita)) {
         if (tamañoHuecos > 12) {
               setSize(grande, getHeight());
                setLocationRelativeTo(null);
            panelBotones.setLayout(new java.awt.GridLayout(5, 1, 15, 15));

         }
         timerCierraAviso.stop();
         boton.setEnabled(false);
         boton.setText(boton.getText() + " " + Global.trad.valor("ocupado"));
         DlgMensajeGenerico msg = new DlgMensajeGenerico(this.padre);
         msg.setLinea1(Global.trad.valor("Servicios con Cita Previa"));
         msg.setLinea2(Global.trad.valor("horaYaOcupada"));
         msg.setLinea3(Global.trad.valor("intenteloDeNuevo"));
         msg.centrarLineas(true, true, true);
         msg.setVisible(true);
         timerCierraAviso.start();
         return true;
      }
      return false;
   }

   public void cargar(RegistroHuecos[] regst, String descripcion) {
      pos = 0;
      regs = regst;
      this.jButton2.setVisible(false);
      tamañoHuecos = regs.length;
      maxhuecos = tamañoHuecos;
      if (tamañoHuecos > 20) {
         setSize(grande, getHeight());
         setLocationRelativeTo(null);
         panelBotones.setLayout(new java.awt.GridLayout(5, 1, 15, 15));
         jButton2.setVisible(true);
         maxhuecos = 20;
      }
      rotulo = descripcion;
      lbNombreServicio.setText(descripcion);
      pintarHuecos();
   }

   public void pintarHuecos() {
      timerCierraAviso.stop();
      timerCierraAviso.start();
      panelBotones.removeAll();
      panelBotones.invalidate();
      panelBotones.validate();
      int posactual = pos;
      if (pos >= tamañoHuecos) {
         pos = 0;
      }
      for (int i = pos; i < (maxhuecos + posactual); i++) {
         JButton boton = new JButton();
         boton.putClientProperty("hueco", regs[i]);
         boton.setText(Fecha.formatoHoraHM(regs[i].horaCita));
         boton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               JButton yo = (JButton) e.getSource();
               confirmarYTerminar(yo);
            }
         });
         Font f = lbNombreServicio.getFont();
         boton.setFont(f.deriveFont(f.getSize2D() * .8f));
         boton.setFocusable(false);
         panelBotones.add(boton);
         pos = i + 1;
         if (pos >= tamañoHuecos) {
            pos = 0;
            panelBotones.revalidate();
            panelBotones.repaint();
            return;
         }
      }
      if (pos >= tamañoHuecos) {
         pos = 0;
      }
      panelBotones.revalidate();
      panelBotones.repaint();
   }

   public void setpulsadorAutomatico(boolean automatico) {
      pulsadorAutomatico = automatico;
   }

   void pulsadoCancelar() {
      regSeleccionado = null;
      setVisible(false);
   }

   void pulsadoAutomatico() {
      JButton primerBotonCita = (JButton) panelBotones.getComponent(0);
      confirmarYTerminar(primerBotonCita);
      pulsadorAutomatico = false;
   }

   void eventoShow() {
      if (pulsadorAutomatico) {
         pulsadoAutomatico();
      }
   }

   /** 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() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new SmoothLabel();
        lbNombreServicio = new SmoothLabel();
        panelBotones = new MiPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new MiBoton();
        jButton2 = new MiBoton();
        jLabel2 = new SmoothLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setUndecorated(true);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204), 4));

        jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 32));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText(Global.trad.valor("HorasDisponibles"));

        lbNombreServicio.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 36));
        lbNombreServicio.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        panelBotones.setLayout(new java.awt.GridLayout(4, 1, 15, 15));

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 70, 8));

        jButton1.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 28)); // NOI18N
        jButton1.setText(Global.trad.valor("cancelar"));
        jButton1.setMinimumSize(new java.awt.Dimension(250, 41));
        jButton1.setPreferredSize(new java.awt.Dimension(250, 65));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);

        jButton2.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 28)); // NOI18N
        jButton2.setForeground(new java.awt.Color(51, 51, 255));
        jButton2.setText(Global.trad.valor("masHoras"));
        jButton2.setMinimumSize(new java.awt.Dimension(250, 41));
        jButton2.setPreferredSize(new java.awt.Dimension(250, 65));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 32));
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText(Global.trad.valor("seleccioneHora"));

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, lbNombreServicio, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
                            .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
                            .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, panelBotones, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 859, Short.MAX_VALUE)))
                    .add(jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 869, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lbNombreServicio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 49, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(panelBotones, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 338, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

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

        pack();
    }// </editor-fold>//GEN-END:initComponents
   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
      pulsadoCancelar();
   }//GEN-LAST:event_jButton1ActionPerformed

   private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
      eventoShow();
   }//GEN-LAST:event_formComponentShown

   private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
      pintarHuecos();
   }//GEN-LAST:event_jButton2ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lbNombreServicio;
    private javax.swing.JPanel panelBotones;
    // End of variables declaration//GEN-END:variables
}
