package puntocassa;

import SmartCard.ISO7816Response;
import SmartCard.SmartCard;
import SmartCard.StringUtil;
import javax.smartcardio.CardException;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.swing.JOptionPane;
import puntocassa.utils.Utils;

/*
 * 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.
 */
/**
 *
 * @author Marco
 */
public class MyApplication {

    public static String path = "";// System.getProperty("user.dir") + "/db/MyFactoryDB.sqlite";
    //public static String elencoRigheDivisori = "";
    //public static String elencoColonneFloat = "";
    public static String elencoColonneReport = "";
    public static String reportColonnaGroupBy = "";
    public static String reportColonnaSomma = "";
    public static SmartCard smartCard = new SmartCard();
    public static String idTesseraA = "";
    public static String ultimoTxt = " ";
    public static Boolean tastieraVideo = true;
    public static Boolean unaVolta = false;

    

   

    /*public String mySelect(PuntoCassa frmA, String query, String campo) {
        String res = "";
        try {
            Connection dbConnection = DriverManager.getConnection(frmA.dbStringa, frmA.dbUsername, frmA.dbPassword);
            Statement st = dbConnection.createStatement();
            ResultSet rs = st.executeQuery(query);
            while (rs.next()) {

                res = rs.getString(campo);
            }
            rs.close();
            st.close();
            dbConnection.close();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(frmA, "Errore MySelect ['" + e.getMessage() + " " + query + "']");

        }
        if (res == null) {
            res = "";
        }
        return res;
    }*/

    /*public String exportCSV(Object[][] data, String[] cols, String[] colType, int colInizio) {
        StringBuilder s = new StringBuilder("");
        DecimalFormat df = new DecimalFormat("#0.00");
        for (int i = colInizio; i < cols.length; i++) {
            s.append(cols[i]).append(";");
        }
        s.append("\r");
        for (Object[] data1 : data) {
            for (int c = colInizio; c < cols.length; c++) {
                if (data1[c] == null) {
                    s.append(";");
                } else {
                    String field = data1[c].toString().replace("\r", " ");
                    if (colType[c].equalsIgnoreCase("integer")) {
                        Integer in = Integer.valueOf(field);
                        if (in == 0) {
                            field = "";
                        } else {
                            field = "" + in;
                        }

                    } else if (colType[c].equalsIgnoreCase("float")) {
                        Float in = Float.valueOf(field);
                        if (in == 0) {
                            field = "";
                        } else {
                            field = "" + df.format(in);
                        }

                    } else if (colType[c].equalsIgnoreCase("boolean")) {
                        Boolean in = Boolean.valueOf(field);
                        if (in == true) {
                            field = "Si";
                        } else {
                            field = "No";
                        }

                    }
                    field = field.replace("\n", " ");
                    field = field.replace(";", ",");
                    s.append(field).append(";");
                }
            }
            s.append("\r");
        }

        return s.toString();
    }*/

    public static String sendAPDU(PuntoCassa frmATT, String sData, String sCla, String sIns, 
                                    String sP1, String sP2, String sP3, String sLe) throws CardException {
        CommandAPDU apdu;

        if (!smartCard.isConnected()) {
            JOptionPane.showMessageDialog(frmATT, new Exception("Please connect first"), "Exception", JOptionPane.ERROR_MESSAGE);
            return "";
        }

        Integer cla = StringUtil.parseHex(sCla);
        Integer ins = StringUtil.parseHex(sIns);
        Integer p1 = StringUtil.parseHex(sP1);
        Integer p2 = StringUtil.parseHex(sP2);
        Integer p3 = StringUtil.parseHex(sP3);
        Integer le = StringUtil.parseHex(sLe);

        if (cla == null) {
            JOptionPane.showMessageDialog(frmATT, new Exception("Invalid value for CLASS"), "Exception", JOptionPane.ERROR_MESSAGE);
            return "";
        }
        if (ins == null) {
            JOptionPane.showMessageDialog(frmATT, new Exception("Invalid value for INS"), "Exception", JOptionPane.ERROR_MESSAGE);
            return "";
        }
        if (p1 == null || p2 == null) {
            JOptionPane.showMessageDialog(frmATT, new Exception("Invalid value for P1/2"), "Exception", JOptionPane.ERROR_MESSAGE);

            return "";
        }

        byte[] data = StringUtil.stringToByteArr(sData);

        if (sData.length() == 0 && le == null) {
            apdu = new CommandAPDU(cla, ins, p1, p2);
        } else if (p3 == null && le == null) {
            apdu = new CommandAPDU(cla, ins, p1, p2, data);
        } else if (le == null) {
            apdu = new CommandAPDU(cla, ins, p1, p2, data, 0, p3);
        } else {
            if (p3 == null) {
                p3 = data.length;
            }
            apdu = new CommandAPDU(cla, ins, p1, p2, data, 0, p3, le);
        }

        ResponseAPDU res = smartCard.getChannel().transmit(apdu);

        String sw = StringUtil.byteToHex(res.getSW1()) + " " + StringUtil.byteToHex(res.getSW2());
        ISO7816Response isoResp = new ISO7816Response(res.getSW1(), res.getSW2());
        String status = isoResp.toString();

       
        String CF = "", DS;
        if (sLe.length() > 0 && Integer.parseInt(sLe) == 140) {
            String dati = StringUtil.byteArrToPrintableString(res.getBytes());
            if (dati.length() >= 47) {
                idTesseraA = dati.substring(12, 26).replace(".", "");
                CF = dati.substring(31, 47);
                DS = Utils.trovaScadenza(dati);//data scadenza
                CF = CF + "|" + DS;
            }
            return CF;
        }
        if (sLe.length() > 0 && Integer.parseInt(sLe) == 14) {
            String dati = StringUtil.byteArrToPrintableString(res.getBytes());
            StringBuilder s = new StringBuilder();
            if (dati.length() >= 16) {
                s.append(dati.substring(4, 16)).append("\n");
                idTesseraA = idTesseraA + dati.substring(4, 13) + Utils.luhn(idTesseraA + dati.substring(4, 13));
            }
        }
        return idTesseraA;
    }

    

    /*public String aggiustaDateTessera(String data) {
        String newData = "";
        if (data.length() >= 8) {
            String m, d, a;
            m = data.substring(4, 6);
            d = data.substring(6, 8);
            a = data.substring(0, 4);
            newData = d + "/" + m + "/" + a;

        }

        return newData;

    }*/

    
}
