/*
 * 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.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;

/**
 *
 * @author Marco
 */
public class MyDialog extends JDialog {

    PuntoCassa frmPuntoCassa;
    JPnlPagamenti panel = new JPnlPagamenti();

    public MyDialog() {
        super();
    }

    public MyDialog(PuntoCassa puntoC, String title, boolean modal) {
        super(puntoC, title, modal);
        frmPuntoCassa = puntoC;
        this.getContentPane().add(panel);

        caricaCombo("Select nome,id from tipi_pagamenti where id<>0 order by nome", "nome", "id", panel.jCmbCat);

        JButton btn = panel.jBtnAggiorna;
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ComboItem c = new ComboItem(null, null);
                c = (ComboItem) panel.jCmbCat.getSelectedItem();

                frmPuntoCassa.idModoPagamento = c.getKey();
                frmPuntoCassa.clickModoPagamento(c.getValue().toString());
                MyDialog.this.dispose();

            }
        });

        JButton jBtnAnnulla = panel.jBtnAnnulla;
        jBtnAnnulla.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frmPuntoCassa.clickCarta();
                MyDialog.this.dispose();

            }
        });

    }

    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());
        }

    }
}
