/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package adgsyncms;

import adgsyncms.service.ADGSyncMS;
import java.awt.Container;
import javax.swing.JFrame;
import adgsyncms.repository.message;
import adgsyncms.repository.repository;
import adgsyncms.service.Email;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import java.util.HashMap;

/**
 *
 * @author amartinez
 */
public class MainJFrame extends javax.swing.JFrame {

    Timer timer = new Timer();
    Timer tmrAlive = new Timer();
    repository repo1 = new repository();
    
    protected int minutos = 0;
    public int hora_entrada = 0, minutos_entrada = 0, hora_salida = 0, minutos_salida = 0, minutos_notificacion = 0,
            hora_inicio_sync_ventas = 0, minutos_inicio_sync_ventas = 0,
            hora_final_sync_ventas = 0, minutos_final_sync_ventas = 0;
    public String mail_notify = "";

    /**
     * Creates new form MainJFrame
     */
    public MainJFrame() {
        initComponents();
        
        HashMap hmap = repo1.readSetting(); //repository.readSetting();

        this.minutos = Integer.parseInt(hmap.get("ws_host_minute").toString());
        this.minutos = this.minutos * 1000 * 60;
        this.hora_entrada = Integer.parseInt(hmap.get("work_in_hour").toString());
        this.minutos_entrada = Integer.parseInt(hmap.get("work_in_minutes").toString());
        this.hora_salida = Integer.parseInt(hmap.get("work_out_hour").toString());
        this.minutos_salida = Integer.parseInt(hmap.get("work_out_minutes").toString());
        this.minutos_notificacion = Integer.parseInt(hmap.get("notify_alive_minutes").toString());
        this.minutos_notificacion = this.minutos_notificacion * 1000 * 60;
        this.mail_notify = hmap.get("notify_alive_mail").toString().trim();
//Para sincronizacion de las ventas
        this.hora_inicio_sync_ventas = Integer.parseInt(hmap.get("start_hour").toString());
        this.minutos_inicio_sync_ventas = Integer.parseInt(hmap.get("start_minute").toString());
        this.hora_final_sync_ventas = Integer.parseInt(hmap.get("end_hour").toString());
        this.minutos_final_sync_ventas = Integer.parseInt(hmap.get("end_minute").toString());

        this.setLocationRelativeTo(null);

        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                Calendar oCalendar = Calendar.getInstance();

                int hora_dia = oCalendar.get(Calendar.HOUR_OF_DAY) * 100;
                int minutos_dia = oCalendar.get(Calendar.MINUTE);
                int hora = hora_dia + minutos_dia;

                if (hora >= (hora_entrada * 100 + minutos_entrada) && (hora <= hora_salida * 100 + minutos_salida)) {
                    if (jButtonGenerateITT.isEnabled()) {
                        synchronize();
                    }
                }
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        };
        timer.schedule(task, 10, this.minutos);

//Tarea para notificacion de funcionamiento
        TimerTask taskAlive = new TimerTask() {

            @Override
            public void run() {
                if (!mail_notify.isEmpty()) {
                    Email eml = new Email();
                    eml.To = mail_notify;
                    eml.setMensaje("ADGSyncMS esta corriendo y funcionando.\n" + jLabelMessage.getText());
                    eml.setSubject("Funcionando");
                    eml.EnviarCorreo();
                }
//                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        };
        tmrAlive.schedule(taskAlive, 20, this.minutos_notificacion);
    }

    public boolean synchronize() {

        jTextArea1.setText("");
        jLabelDescription.setText("");

        jButtonGenerateITT.setEnabled(false);
        jButtonExit.setEnabled(false);

        //message.setCaption(jLabelMessage, "Preparado...");
        ADGSyncMS sync = new ADGSyncMS();
        sync.sincronizar(jTextArea1, jLabelDescription);

        message.setCaption(jLabelMessage, "Ultima sincronizacion: " + Calendar.getInstance().getTime().toString());
        jLabelDescription.setText("");

        jButtonGenerateITT.setEnabled(true);
        jButtonExit.setEnabled(true);

        return false;
    }


    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonExit = new javax.swing.JButton();
        jButtonGenerateITT = new javax.swing.JButton();
        jLabelDescription = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jLabelMessage = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ADGSyncMS - Master to Slave Sync");
        setBackground(new java.awt.Color(99, 149, 246));
        setFont(new java.awt.Font("Arial", 1, 10)); // NOI18N
        setForeground(java.awt.Color.blue);
        setMinimumSize(new java.awt.Dimension(470, 490));
        setPreferredSize(new java.awt.Dimension(472, 480));
        setSize(new java.awt.Dimension(0, 0));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jButtonExit.setBackground(javax.swing.UIManager.getDefaults().getColor("Button.focus"));
        jButtonExit.setFont(new java.awt.Font("Arial", 1, 15)); // NOI18N
        jButtonExit.setText("Salir");
        jButtonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExitActionPerformed(evt);
            }
        });
        getContentPane().add(jButtonExit, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 390, 140, 40));

        jButtonGenerateITT.setBackground(javax.swing.UIManager.getDefaults().getColor("Actions.Green"));
        jButtonGenerateITT.setFont(new java.awt.Font("Arial", 1, 15)); // NOI18N
        jButtonGenerateITT.setText("Sincronizar");
        jButtonGenerateITT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGenerateITTActionPerformed(evt);
            }
        });
        getContentPane().add(jButtonGenerateITT, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 390, 140, 40));

        jLabelDescription.setText("-");
        getContentPane().add(jLabelDescription, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 208, 450, 20));
        getContentPane().add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 380, 470, 10));
        getContentPane().add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 340, 470, -1));

        jLabelMessage.setText("...");
        jLabelMessage.setName(""); // NOI18N
        getContentPane().add(jLabelMessage, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 340, 450, 30));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/adgsyncms/resource/adg-logo.jpg"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 12, -1, 170));
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 590, -1, -1));

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 460, 110));

        jLabel3.setText("v. 12-06-2025");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 400, -1, -1));

        jLabel4.setForeground(new java.awt.Color(0, 153, 255));
        jLabel4.setText("Sincronizacion de Entidades - Master to Slave");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExitActionPerformed
        // TODO add your handling code here:
        Container frame = jButtonExit.getParent();
        do {
            frame = frame.getParent();
        } while (!(frame instanceof JFrame));
        ((JFrame) frame).dispose();

        System.exit(0);
    }//GEN-LAST:event_jButtonExitActionPerformed

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonExit;
    private javax.swing.JButton jButtonGenerateITT;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabelDescription;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
