/* 
* 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.utiles.*;
import java.awt.*;
import java.io.*;
import java.util.jar.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public final class FormAyuda extends javax.swing.JDialog {

   PanelTactil padre;
   public String colaSolicitada;
   Timer timer;

   public FormAyuda(PanelTactil padre, Font fuenteBoton) {
      super(padre, true);
      this.padre = padre;
      //extraerGraficosJar();
      initComponents();
      this.setSize((int) ((float) Toolkit.getDefaultToolkit().getScreenSize().getWidth() * .85),
              (int) ((float) Toolkit.getDefaultToolkit().getScreenSize().getHeight() * .80));
      this.setLocationRelativeTo(padre);
      if (!Configuracion.instanciaUnica().cursorVisible) {
         setCursor(gestor.utiles.Global.mainForm.cursorTransparente);
      }

      timer = new Timer(Configuracion.instanciaUnica().segundosAyuda * 1000, new java.awt.event.ActionListener() {
         @Override
         public void actionPerformed(java.awt.event.ActionEvent e) {
            cerrar();
         }
      });

      html.setContentType("text/html");
      DefaultCaret caret = (DefaultCaret)html.getCaret();
      caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
      ajustes(fuenteBoton);
   }

   void extraerGraficosJar() {
      try {
         JarFile jar = new JarFile("Autoservicio.jar");
         //extraer("ayuda/cartel_dnie.jpg", jar);
         extraer("ayuda/cabecera.jpg", jar);
         jar.close();
      } catch (Exception exc) {
         exc.printStackTrace();
      }
   }

   private void extraer(String path, JarFile jar) {
      try {
         JarEntry entrada = jar.getJarEntry(path);
         if (entrada == null) {
            return;
         }
         File salida = new File(path);
         long fechaInterna = entrada.getTime();
         if (salida.exists()) {
            long fechaExterna = salida.lastModified();
            if (fechaInterna == fechaExterna) {
               return;
            }
         }
         InputStream is = new BufferedInputStream(jar.getInputStream(entrada));
         OutputStream os = new BufferedOutputStream(new FileOutputStream(salida));
         byte[] bufer = new byte[2048];
         for (;;) {
            int nBytes = is.read(bufer);
            if (nBytes <= 0) {
               break;
            }
            os.write(bufer, 0, nBytes);
         }
         os.flush();
         os.close();
         salida.setLastModified(fechaInterna);
      } catch (IOException exc) {
      }
   }

   public void iniciar() {
      timer.start();
      cargarMenu();
      btCerrar2.setVisible(false);
      setVisible(true);
   }

   public void iniciarEnColaEspecifica(String cola) {
      timer.start();
      colaSolicitada = cola;
      if (!gestor.datos.TablaColas.getTablaColas().contieneCola(cola))
      {
          btTicket.setVisible(false);
      }
      String texto = Global.generadorAyuda.pagina(cola);
      if (texto.equals("")) {
         texto = Global.generadorAyuda.generarPaginaVacia(cola);
      }
      html.setText(texto);
      panelBotones.setVisible(true);
      btMenu.setVisible(false);
      GeneradorAyuda.DatoXml datosAyuda = Global.generadorAyuda.datosayuda(cola);
      if (datosAyuda != null && !datosAyuda.tique) {
         // gestor.datos.RegistroColas regCola = gestor.datos.TablaColas.getTablaColas().buscar(cola);
         // if(regCola.cerrada) {
         btTicket.setVisible(false);
         // btCerrar2.setVisible(true);
      }
      setVisible(true);
   }

   public void ajustes(Font fuenteBoton) {
      Font miFuente = fuenteBoton.deriveFont(fuenteBoton.getSize2D() * .8f);
      btMenu.setFont(miFuente);
      btMenu.setText(Global.trad.valor("VolverAlMenu"));
      btTicket.setFont(miFuente);
      btTicket.setText(Global.trad.valor("ObtenerTicket"));
      btCerrar.setFont(miFuente);
      btCerrar.setText(Global.trad.valor("Cerrar"));
      btCerrar2.setFont(miFuente);
      btCerrar2.setText(Global.trad.valor("Cerrar"));
      lbTitulo.setFont(fuenteBoton.deriveFont(36f));
      lbTitulo.setText(Global.trad.valor("Ayuda"));
   }

   void cargarMenu() {
      timer.restart();
      html.setText(Global.generadorAyuda.pagina("menu"));
      this.panelBotones.setVisible(false);
   }

   void navegar(javax.swing.event.HyperlinkEvent evt) {
      try {
         if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
            timer.restart();
            String destino = evt.getDescription();
            if (destino.startsWith("cola=")) {
               colaSolicitada = destino.substring(5);
               html.setText(Global.generadorAyuda.pagina(colaSolicitada));
               GeneradorAyuda.DatoXml datosAyuda = Global.generadorAyuda.datosayuda(colaSolicitada);
               btTicket.setVisible(datosAyuda.tique);
               gestor.datos.RegistroCola regCola = gestor.datos.TablaColas.getTablaColas().buscar(colaSolicitada);
               if (regCola != null && regCola.colaEspecial) {
                  btTicket.setVisible(false);
               }
               html.scrollRectToVisible(new Rectangle(0,0,1,1));
            } else {
               try {
                  html.setPage(destino);
               } catch (Exception exc) {
               }
            }
            this.panelBotones.setVisible(true);
         }
      } catch (Exception extc) {
      }
   }

   void cerrar() {
      colaSolicitada = null;
      timer.stop();
      this.setVisible(false);
   }

   void solicitadoTicket() {
      timer.stop();
      this.setVisible(false);
   }

   void resetTimer() {
      timer.restart();
   }

   /**
    * 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();
      panelSuperior = new javax.swing.JPanel();
      btCerrar = new gestor.utiles.MiBoton();
      lbTitulo = new gestor.utiles.SmoothLabel();
      panelHtml = new javax.swing.JPanel();
      jScrollPane1 = new javax.swing.JScrollPane();
      html = new javax.swing.JEditorPane();
      panelBotones = new javax.swing.JPanel();
      btTicket = new gestor.utiles.MiBoton();
      btMenu = new gestor.utiles.MiBoton();
      btCerrar2 = new gestor.utiles.MiBoton();

      setUndecorated(true);
      addMouseListener(new java.awt.event.MouseAdapter() {
         public void mousePressed(java.awt.event.MouseEvent evt) {
            formMousePressed(evt);
         }
      });
      addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
         public void mouseMoved(java.awt.event.MouseEvent evt) {
            formMouseMoved(evt);
         }
      });
      addKeyListener(new java.awt.event.KeyAdapter() {
         public void keyPressed(java.awt.event.KeyEvent evt) {
            formKeyPressed(evt);
         }
      });

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

      panelSuperior.setBackground(new java.awt.Color(153, 153, 153));
      panelSuperior.setMaximumSize(new java.awt.Dimension(32767, 75));
      panelSuperior.setMinimumSize(new java.awt.Dimension(10, 75));
      panelSuperior.setPreferredSize(new java.awt.Dimension(10, 75));

      btCerrar.setText("Cerrar");
      btCerrar.setFocusable(false);
      btCerrar.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btCerrarActionPerformed(evt);
         }
      });

      lbTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
      lbTitulo.setText("Ayuda");

      org.jdesktop.layout.GroupLayout panelSuperiorLayout = new org.jdesktop.layout.GroupLayout(panelSuperior);
      panelSuperior.setLayout(panelSuperiorLayout);
      panelSuperiorLayout.setHorizontalGroup(
         panelSuperiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(org.jdesktop.layout.GroupLayout.TRAILING, panelSuperiorLayout.createSequentialGroup()
            .add(36, 36, 36)
            .add(lbTitulo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 316, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 278, Short.MAX_VALUE)
            .add(btCerrar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .add(27, 27, 27))
      );
      panelSuperiorLayout.setVerticalGroup(
         panelSuperiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelSuperiorLayout.createSequentialGroup()
            .addContainerGap()
            .add(panelSuperiorLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(btCerrar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(lbTitulo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 53, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
      );

      jPanel1.add(panelSuperior, java.awt.BorderLayout.NORTH);

      panelHtml.setPreferredSize(new java.awt.Dimension(100, 80));
      panelHtml.setLayout(new java.awt.BorderLayout());

      jScrollPane1.setBorder(null);

      html.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 100, 1, 100));
      html.setEditable(false);
      html.setDoubleBuffered(true);
      html.setVerifyInputWhenFocusTarget(false);
      html.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
         public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
            htmlHyperlinkUpdate(evt);
         }
      });
      jScrollPane1.setViewportView(html);

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

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

      panelBotones.setBackground(new java.awt.Color(255, 255, 255));
      panelBotones.setMinimumSize(new java.awt.Dimension(0, 0));
      panelBotones.setPreferredSize(new java.awt.Dimension(815, 100));

      btTicket.setText("Obtener Ticket");
      btTicket.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btTicketActionPerformed(evt);
         }
      });

      btMenu.setText("Volver al menú");
      btMenu.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btMenuActionPerformed(evt);
         }
      });

      btCerrar2.setText("Cerrar");
      btCerrar2.setFocusable(false);
      btCerrar2.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            btCerrarActionPerformed(evt);
         }
      });

      org.jdesktop.layout.GroupLayout panelBotonesLayout = new org.jdesktop.layout.GroupLayout(panelBotones);
      panelBotones.setLayout(panelBotonesLayout);
      panelBotonesLayout.setHorizontalGroup(
         panelBotonesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(panelBotonesLayout.createSequentialGroup()
            .addContainerGap()
            .add(btMenu, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
            .add(btCerrar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 143, Short.MAX_VALUE)
            .add(btTicket, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
            .addContainerGap())
      );
      panelBotonesLayout.setVerticalGroup(
         panelBotonesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
         .add(org.jdesktop.layout.GroupLayout.TRAILING, panelBotonesLayout.createSequentialGroup()
            .addContainerGap(31, Short.MAX_VALUE)
            .add(panelBotonesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
               .add(btMenu, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(btCerrar2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
               .add(btTicket, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
            .addContainerGap())
      );

      jPanel1.add(panelBotones, java.awt.BorderLayout.SOUTH);

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

      pack();
   }// </editor-fold>//GEN-END:initComponents
    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
       resetTimer();
    }//GEN-LAST:event_formMouseMoved

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
       resetTimer();
    }//GEN-LAST:event_formMousePressed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
       resetTimer();
    }//GEN-LAST:event_formKeyPressed

    private void btTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTicketActionPerformed
       solicitadoTicket();
    }//GEN-LAST:event_btTicketActionPerformed

    private void btMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMenuActionPerformed
       cargarMenu();
    }//GEN-LAST:event_btMenuActionPerformed

    private void htmlHyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {//GEN-FIRST:event_htmlHyperlinkUpdate
       navegar(evt);
    }//GEN-LAST:event_htmlHyperlinkUpdate

    private void btCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCerrarActionPerformed
       cerrar();
    }//GEN-LAST:event_btCerrarActionPerformed
   // Variables declaration - do not modify//GEN-BEGIN:variables
   private javax.swing.JButton btCerrar;
   private javax.swing.JButton btCerrar2;
   private javax.swing.JButton btMenu;
   private javax.swing.JButton btTicket;
   private javax.swing.JEditorPane html;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JScrollPane jScrollPane1;
   private javax.swing.JLabel lbTitulo;
   private javax.swing.JPanel panelBotones;
   private javax.swing.JPanel panelHtml;
   private javax.swing.JPanel panelSuperior;
   // End of variables declaration//GEN-END:variables
}
