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

import java.awt.Font;
import java.awt.Rectangle;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumn;
import puntocassa.utils.Utils;

/**
 *
 * @author Marco
 */
public class FrmMeteo extends javax.swing.JFrame {

   private PuntoCassa frmPuntoCassa;
   private Long idPuntoCassa=0L;
   private Boolean Inserimento=false;
   public int HFont=15;
   private int AltControlli=100;
   private int LargControlli=100;
   private int AltRigaGriglia=0;
   
    /**
     * Creates new form frm
     */
    public FrmMeteo(PuntoCassa frm, Long id_Punto_Cassa,Boolean Nuovo) {

        frmPuntoCassa=frm;
        frmPuntoCassa.setEnabled(false);
        //KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(frmPuntoCassa.keyDispatcher);  
        frmPuntoCassa.addRemoveKeyDispatcher(false);
        idPuntoCassa=id_Punto_Cassa;
        Inserimento=Nuovo;
        initComponents();
        String startDir = System.getProperty("user.dir");
        File IconaApp = new File(startDir + "/risorse/logo.png");
        if (IconaApp.exists()) {

            ImageIcon icon = new ImageIcon(startDir + "/risorse/logo.png");
            this.setIconImage(icon.getImage());
        }
        CaricaCombo("Select nome,id from condizioni_meteo order by nome", "nome", "id", jCmbCat);
        
    }

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

        pnl1 = new javax.swing.JPanel();
        jBtnAggiorna = new javax.swing.JButton();
        jCmbCat = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Aggiorna condizioni Meteo");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jBtnAggiorna.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jBtnAggiorna.setText("Aggiorna");
        jBtnAggiorna.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnAggiornaActionPerformed(evt);
            }
        });

        jCmbCat.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jCmbCat.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout pnl1Layout = new javax.swing.GroupLayout(pnl1);
        pnl1.setLayout(pnl1Layout);
        pnl1Layout.setHorizontalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl1Layout.createSequentialGroup()
                .addComponent(jCmbCat, 0, 238, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jBtnAggiorna, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6))
        );
        pnl1Layout.setVerticalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCmbCat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBtnAggiorna))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void ClearTable(MyTableModel model) {
        try {
            for (Integer i = model.getRowCount() - 1; i >= 0; i--) {
                model.deleteRow(i);
            }
        } catch (Exception e) {
        }
    }
    private void Tastiera(JTextField jTxt,Integer MyX,Integer MyY){
    
        MyKeyBoard myk=new MyKeyBoard(this,false);
        myk.txt=jTxt;
        myk.parent=this;
        Rectangle s=this.getBounds();
        Rectangle s2=jTxt.getBounds();
        Integer l=s.x+s2.x+MyX;
        if(l+800>s.x+s.width){l=s.x+s.width-800;}
        myk.setBounds(l,s.y+s2.y+60+MyY, 800, 300);
        myk.setVisible(true);

    }
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {
            frmPuntoCassa.setEnabled(true);
            //KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(frmPuntoCassa.keyDispatcher);
            frmPuntoCassa.addRemoveKeyDispatcher(true);
            frmPuntoCassa.toFront();
            frmPuntoCassa.repaint();

            frmPuntoCassa = null;
            this.dispose();
        } catch (Exception ex) {

        }
    }//GEN-LAST:event_formWindowClosed

    private void jBtnAggiornaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnAggiornaActionPerformed
        ComboItem c = new ComboItem(null, null);
        c = (ComboItem) jCmbCat.getSelectedItem();
        if (Inserimento) {
            MyInsert("insert into meteo (id_Punto_Cassa,id_Condizioni) values (" + idPuntoCassa + "," + c.getKey() + ")");
        } else {
            Date Adesso=new Date();
            MyInsert("Update meteo set id_Condizioni=" + c.getKey() + " where id_Punto_Cassa=" + 
                    idPuntoCassa + " and to_date(ts_segnalazione,'dd/mm/yy')=" + AggiustaData(Adesso));
        }
        this.dispose();
    }//GEN-LAST:event_jBtnAggiornaActionPerformed
    
    private String AggiustaData(Date Data) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String data = "to_date('" + formatter.format(Data) + "','dd/mm/yyyy')";
        return data;
    }
    
    private Boolean MyInsert(String Query) {
        Boolean res=false;
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);  
            Statement st = dbConnection.createStatement();
            ResultSet rs = st.executeQuery(Query);
            rs.close();
            st.close();
            dbConnection.close();
            res=true;
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Errore MySelect ['" + e.getMessage() + " " + Query + "']");
            
        }
        return res;
    }   
    private void QueryDati(String Query,String QueryCount,String[] Colonne,String[] ColType, JTable jTbl,Boolean Editable){
     try{
        MyApplication MyA=new MyApplication();
        MyTableModel model = new MyTableModel( );
        model.setColumname(Colonne);
        
//        model.setEditable(Editable);
//        int [] colBool=new int[1];
//        colBool[0]=7;
//        model.setColBoolean(colBool);
//        int[] cols=new int[1];
//        cols[0]=7;
//        model.setColModificabile(cols);
        int rowCount=Integer.parseInt(Utils.mySelect(QueryCount, "righe", frmPuntoCassa));
        Object[][] data = RowData(Query, Colonne,ColType,rowCount);
        model.setData(data);

        try{jTbl.setModel(model);}catch(Exception e){}
        jTbl.setAutoCreateColumnsFromModel(true);

        jTbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTbl.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 16));
        jTbl.setFont(new Font("Tahoma", 0, 16));
        
        
        TableColumn column = jTbl.getColumn("id");
        column.setMinWidth(0);
        column.setMaxWidth(0);
        column.setWidth(0);
        column.setPreferredWidth(0);
        
        model.fireTableDataChanged();
        
        doLayout();
     }catch(NumberFormatException e){
     
        System.out.println("Query: " + e.getMessage());
     }
     
    } 
     private Integer CalcolaLarghezzaAltezza(Integer LarControllo,Integer Percentuale){
      Integer D = Percentuale - 100;
      if (D == 0) {
          return LarControllo;
      } else {
          Integer N = LarControllo + ((LarControllo * D) / 100);
          return N;
      }
  
  }
    public Object[][] RowData(String Query, String[] Cols, String[] ColType, int rowCount) {
        Object[][] rows = null;
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);  
            Statement st = dbConnection.createStatement();
            ResultSet rs = st.executeQuery(Query);
            rows = new Object[rowCount][];
            int r = 0;
            while (rs.next()) {
                Object[] row = new Object[Cols.length];
                for (int i = 0; i < Cols.length; i++) {
                    if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                        row[i] = "";
                    } else {
                        row[i] = rs.getString(Cols[i].replace(" ", "_"));
                    }
                    switch (ColType[i]) {
                        case "text":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = "";
                            } else {
                                row[i] = rs.getString(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "integer":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = 0;
                            } else {
                                row[i] = rs.getInt(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "boolean":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = false;
                            } else {
                                row[i] = rs.getBoolean(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "float":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = 0.00;
                            } else {
                                String v = rs.getString(Cols[i].replace(" ", "_"));

                                row[i] = Float.parseFloat(v.replace(",", "."));
                            }

                            break;
                            
                         case "data":
                            row[i] = "";
                            if (rs.getString(Cols[i].replace(" ", "_")) != null) {
//                                Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ITALY).parse(rs.getString(Cols[i]));
                                //SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                                String[] d= rs.getString(Cols[i].replace(" ", "_")).split("-");
                                if (d.length>=3){
                                    row[i] = d[2].trim().substring(0, 2) + "/" + d[1] + "/" + d[0];
                                }
                            }

                            break;
                    }

                }
                rows[r] = row;
                r++;
                /*int id = rs.getInt("id");
                 String  name = rs.getString("name");
                 int age  = rs.getInt("age");
                 String  address = rs.getString("address");
                 float salary = rs.getFloat("salary");*/

            }
            rs.close();
            st.close();


        } catch (SQLException | NumberFormatException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        } finally {

            return rows;
        }

    }  
    /**
     * @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(FrmMeteo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmMeteo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmMeteo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmMeteo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmMeteo(null,0L,true).setVisible(true);
            }
        });
    }
    private void CaricaCombo (String Query, String itemValue, String itemId, JComboBox cmb) {
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);  
            Connection c = dbConnection;
            Statement stmt = null;
            cmb.removeAllItems();
            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery(Query);
            int r = 0;
            while (rs.next()) {
                
                ComboItem row=new ComboItem(rs.getLong(itemId), rs.getString(itemValue)) ;
                cmb.addItem(row);

                r++;

            }
            rs.close();
            stmt.close();
            dbConnection.close();

        } catch (SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        } 

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnAggiorna;
    private javax.swing.JComboBox jCmbCat;
    private javax.swing.JPanel pnl1;
    // End of variables declaration//GEN-END:variables
}
