/*
 * 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.Image;
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 javax.swing.ImageIcon;
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 FrmStorno extends javax.swing.JFrame {

    private PuntoCassa frmPuntoCassa;
    private Long idTessera = 0L, idPuntoCassa = 0L;
    public int hFont = 15;
    private int altRigaGriglia = 0;
    private Boolean azzera = false;
    private Boolean stornoEffettuato = false;

    /**
     * Creates new form frm
     *
     * @param frm
     * @param idTessera
     * @param idPuntoCassa
     * @param imgPath
     * @param azzera
     */
    public FrmStorno(PuntoCassa frm, Long idTessera, Long idPuntoCassa, String imgPath, Boolean azzera) {

        frmPuntoCassa = frm;
        frmPuntoCassa.setEnabled(false);
        frmPuntoCassa.addRemoveKeyDispatcher(false);

        this.idPuntoCassa = idPuntoCassa;
        this.idTessera = idTessera;
        this.azzera = azzera;
        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());
        }

        ImageIcon icon = new ImageIcon(imgPath + "freccia_down.jpg");
        Image img = icon.getImage();
        Image newimg = img.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
        icon = new ImageIcon(newimg);
        jbtnGiu.setIcon(icon);

        ImageIcon icon2 = new ImageIcon(imgPath + "freccia_up.jpg");
        Image img2 = icon2.getImage();
        Image newimg2 = img2.getScaledInstance(50, 50, java.awt.Image.SCALE_SMOOTH);
        icon2 = new ImageIcon(newimg2);
        jbtnSu.setIcon(icon2);
        aggiorna();

    }

    /**
     * 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();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTblStudenti = new javax.swing.JTable();
        jbtnAnnulla = new javax.swing.JButton();
        jLblTitolo = new javax.swing.JLabel();
        jBtnOK = new javax.swing.JButton();
        jbtnSu = new javax.swing.JButton();
        jbtnGiu = new javax.swing.JButton();

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

        jTblStudenti.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jTblStudenti.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane3.setViewportView(jTblStudenti);

        jbtnAnnulla.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jbtnAnnulla.setText("Annulla");
        jbtnAnnulla.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAnnullaActionPerformed(evt);
            }
        });

        jLblTitolo.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLblTitolo.setForeground(new java.awt.Color(255, 0, 0));
        jLblTitolo.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLblTitolo.setText("Storno");

        jBtnOK.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jBtnOK.setText("Storna");
        jBtnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnOKActionPerformed(evt);
            }
        });

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

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

        javax.swing.GroupLayout pnl1Layout = new javax.swing.GroupLayout(pnl1);
        pnl1.setLayout(pnl1Layout);
        pnl1Layout.setHorizontalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addComponent(jLblTitolo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(8, 8, 8))
            .addGroup(pnl1Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 768, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnSu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnGiu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGroup(pnl1Layout.createSequentialGroup()
                .addComponent(jBtnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnAnnulla, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pnl1Layout.setVerticalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addComponent(jLblTitolo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jbtnSu, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnGiu, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnAnnulla, javax.swing.GroupLayout.DEFAULT_SIZE, 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)
            .addGap(0, 850, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(6, 6, 6)
                    .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 307, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );

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

    private void jbtnAnnullaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAnnullaActionPerformed

        this.dispose();
    }//GEN-LAST:event_jbtnAnnullaActionPerformed
    

    
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {

            frmPuntoCassa.setEnabled(true);
            frmPuntoCassa.addRemoveKeyDispatcher(true);
            frmPuntoCassa.toFront();
            frmPuntoCassa.repaint();
            if (azzera && stornoEffettuato == false) {
                frmPuntoCassa.azzeraDopoStorno();
            }
            frmPuntoCassa = null;

            this.dispose();
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_formWindowClosed

    private void jBtnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnOKActionPerformed
        if (jTblStudenti.getSelectedRow() >= 0) {
            MyTableModel model = new MyTableModel();
            model = (MyTableModel) jTblStudenti.getModel();
            Object[] row = model.getRow(jTblStudenti.getSelectedRow());

            Boolean ok = Utils.myInsert("insert into ristorni (ID_TESSERA,ID_PRODOTTO,ID_PUNTO_CASSA,DATA,NUM_PROGRESSIVO,IMPORTO,PUNTI,ID_TIPO_PAGAMENTO,ID_TURNO,FLAG_IN_VASSOIO,SALDO_PRE,SALDO_POST,PUNTI_PRE,PUNTI_POST,FLAG_GRATUITA,FLAG_ASPORTO,FLAG_BONUS,ID_PREN_DETTAGLIO) "
                    + "SELECT ID_TESSERA,ID_PRODOTTO,ID_PUNTO_CASSA,DATA,NUM_PROGRESSIVO,IMPORTO,PUNTI,ID_TIPO_PAGAMENTO,ID_TURNO,FLAG_IN_VASSOIO,SALDO_PRE,SALDO_POST,PUNTI_PRE,PUNTI_POST,FLAG_GRATUITA,FLAG_ASPORTO,FLAG_BONUS,ID_PREN_DETTAGLIO "
                    + "FROM st_acquisti WHERE num_progressivo = " + row[3], this.frmPuntoCassa);
            if (ok) {
                Utils.myInsert("Delete from St_Acquisti where num_progressivo=" + row[3], this.frmPuntoCassa);
                stornoEffettuato = true;
            }

            if (!azzera) {
                frmPuntoCassa.aggiornaProgressivi();
            }

            this.dispose();
        }

    }//GEN-LAST:event_jBtnOKActionPerformed

    private void jbtnSuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSuActionPerformed
        // TODO add your handling code here:
        if (jTblStudenti.getSelectedRow() > 0) {
            jTblStudenti.setRowSelectionInterval(jTblStudenti.getSelectedRow() - 1, jTblStudenti.getSelectedRow() - 1);
            jTblStudenti.scrollRectToVisible(new Rectangle(jTblStudenti.getCellRect(jTblStudenti.getSelectedRow(), 0, true)));
        }
    }//GEN-LAST:event_jbtnSuActionPerformed

    private void jbtnGiuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGiuActionPerformed
        // TODO add your handling code here:
        if (jTblStudenti.getSelectedRow() < jTblStudenti.getRowCount() - 1) {
            jTblStudenti.setRowSelectionInterval(jTblStudenti.getSelectedRow() + 1, jTblStudenti.getSelectedRow() + 1);
            jTblStudenti.scrollRectToVisible(new Rectangle(jTblStudenti.getCellRect(jTblStudenti.getSelectedRow(), 0, true)));
        }

    }//GEN-LAST:event_jbtnGiuActionPerformed
   

    private void queryDati(String query, String queryCount, String[] colonne, String[] colTypes, JTable jTbl) {
        try {
            
            MyTableModel model = new MyTableModel();
            model.setColumname(colonne);

            int rowCount = Integer.parseInt(Utils.mySelect(queryCount, "righe", frmPuntoCassa));
            Object[][] data = rowData(query, colonne, colTypes, 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);

            TableColumn column2 = jTbl.getColumn("idProdotto");
            column2.setMinWidth(0);
            column2.setMaxWidth(0);
            column2.setWidth(0);
            column2.setPreferredWidth(0);

            TableColumn column3 = jTbl.getColumn("id_Tipo_Pagamento");
            column3.setMinWidth(0);
            column3.setMaxWidth(0);
            column3.setWidth(0);
            column3.setPreferredWidth(0);

            TableColumn column4 = jTbl.getColumn("id_Turno");
            column4.setMinWidth(0);
            column4.setMaxWidth(0);
            column4.setWidth(0);
            column4.setPreferredWidth(0);

            TableColumn column1 = jTbl.getColumn("Prodotto");
            column1.setPreferredWidth(280);
            column1.setWidth(280);

            TableColumn column11 = jTbl.getColumn("Data");
            column11.setPreferredWidth(180);
            column11.setWidth(180);

            model.fireTableDataChanged();

            doLayout();
        } catch (NumberFormatException e) {

            System.out.println("Query: " + e.getMessage());
        }

    }

    private void aggiorna() {
        try {
            String fromClause = " from st_acquisti a inner join prodotti p on a.id_prodotto=p.id inner join Tipi_Pagamenti tp on a.id_tipo_pagamento=tp.id ";
            String whereClause = "where TRUNC(data) = TRUNC(SYSDATE) and id_tessera=" + idTessera + " and flag_in_vassoio=0 and id_punto_cassa=" + idPuntoCassa;
            String[] colNames = {"id", "idProdotto", "Data", "Progressivo", "Prodotto", "Importo", "id_Tipo_Pagamento", "id_Turno", "Pagamento"};
            String[] colTypes = {"long", "long", "data", "integer", "text", "float", "long", "long", "text"};
            String QueryCount = "Select count(*) as righe " + fromClause + whereClause;
            queryDati("select a.id,p.id as idProdotto,a.data,a.num_progressivo as Progressivo,p.nome as Prodotto,a.importo,a.id_tipo_pagamento,a.id_turno,tp.Nome as Pagamento " + fromClause + whereClause + " order by a.data desc,a.num_progressivo desc", QueryCount, colNames, colTypes, jTblStudenti);

            Font f = new Font("Tahoma", 0, 18);
            jTblStudenti.setFont(f);
            if (altRigaGriglia == 0) {
                altRigaGriglia = jTblStudenti.getRowHeight();
            }

            jTblStudenti.setRowHeight(25);
            if (jTblStudenti.getRowCount() > 0) {
                jTblStudenti.setRowSelectionInterval(0, 0);

            }

        } catch (Exception e) {
        }
    }
    

    public Object[][] rowData(String query, String[] cols, String[] colTypes, 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 (colTypes[i]) {
                        case "text" -> {
                            if (rs.getString(cols[i].replace(" ", "_")) == null) {
                                row[i] = "";
                            } else {
                                row[i] = rs.getString(cols[i].replace(" ", "_"));
                            }
                        }
                        case "integer" -> {
                            if (rs.getString(cols[i].replace(" ", "_")) == null) {
                                row[i] = 0;
                            } else {
                                row[i] = rs.getInt(cols[i].replace(" ", "_"));
                            }
                        }
                        case "long" -> {
                            if (rs.getString(cols[i].replace(" ", "_")) == null) {
                                row[i] = 0;
                            } else {
                                row[i] = rs.getLong(cols[i].replace(" ", "_"));
                            }
                        }
                        case "boolean" -> {
                            if (rs.getString(cols[i].replace(" ", "_")) == null) {
                                row[i] = false;
                            } else {
                                row[i] = rs.getBoolean(cols[i].replace(" ", "_"));
                            }
                        }
                        case "float" -> {
                            if (rs.getString(cols[i].replace(" ", "_")) == null) {
                                row[i] = 0.00;
                            } else {
                                String v = rs.getString(cols[i].replace(" ", "_"));

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

                        case "data" -> {
                            row[i] = "";
                            if (rs.getString(cols[i].replace(" ", "_")) != null) {

                                String[] d = rs.getString(cols[i].replace(" ", "_")).split("-");
                                if (d.length >= 3) {
                                    String Ora = "";

                                    if (d[2].length() > 8) {
                                        String O[] = d[2].trim().split(" ");
                                        if (O.length > 1) {
                                            if (O[1].length() >= 8) {
                                                Ora = O[1].substring(0, 8);
                                            }
                                        }
                                    }
                                    row[i] = d[2].trim().substring(0, 2) + "/" + d[1] + "/" + d[0] + " " + Ora;
                                }
                            }
                        }
                    }

                }
                rows[r] = row;
                r++;

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmStorno(null, 0L, 0L, null, false).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnOK;
    private javax.swing.JLabel jLblTitolo;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTblStudenti;
    private javax.swing.JButton jbtnAnnulla;
    private javax.swing.JButton jbtnGiu;
    private javax.swing.JButton jbtnSu;
    private javax.swing.JPanel pnl1;
    // End of variables declaration//GEN-END:variables
}
