package ufradvanced;

import java.awt.Color;
import java.awt.Font;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JTable;

import javax.swing.table.*;

public class frmViewAll extends javax.swing.JInternalFrame {

    public frmViewAll() {
        initComponents();
        try{
             M =frmMain.class.newInstance();
        }catch(InstantiationException | IllegalAccessException ie){
            
        }
    }

    final static int FUNCT_LIGHT_OK = 4,
            FUNCT_SOUND_OK = 0,//4 Tripple sound
            FUNCT_LIGHT_ERROR = 2,
            FUNCT_SOUND_ERROR = 0,//2 Long sound
            DL_OK = 0;

    final static byte MIFARE_AUTHENT1A = 0x60,
                     MIFARE_AUTHENT1B = 0x61;

    private enum MAX_SECTORS_PAGES_VALUE {                                               

        MAX_SECTORS_1k(0x10), //16                         
        MAX_SECTORS_4k(0x28), //40   
        MAX_BLOCK_BYTES(0x10), //16

        MAX_PAGE_NTAG203(0x27), //39
        MAX_PAGE_ULTRALIGHT(0x0F),//15 
        MAX_PAGE_ULTRALIGHT_C(0x27);

        private MAX_SECTORS_PAGES_VALUE(int values) {
            this.value = values;
        }
        private int value = 0;

        public int getValue() {
            return value;
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGroup1 = new javax.swing.ButtonGroup();
        btnRead = new javax.swing.JButton();
        chkHex = new javax.swing.JCheckBox();
        lblFunction = new javax.swing.JTextField();
        txtFErrorCode = new javax.swing.JTextField();
        txtFErrorExplain = new javax.swing.JTextField();
        rbAUTH1A = new javax.swing.JRadioButton();
        rbAUTH1B = new javax.swing.JRadioButton();
        lblKeyIndex = new javax.swing.JLabel();
        cboKeyIndex = new javax.swing.JComboBox();
        pBar = new javax.swing.JProgressBar();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        setTitle("frmViewAll");
        setFocusCycleRoot(false);
        setFocusable(false);
        setName("frmViewAll"); // NOI18N
        setNormalBounds(new java.awt.Rectangle(0, 0, 555, 378));
        setPreferredSize(new java.awt.Dimension(555, 385));
        setRequestFocusEnabled(false);
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                formMouseDragged(evt);
            }
        });
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnRead.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        btnRead.setText("READ CARD");
        btnRead.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnRead.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnReadActionPerformed(evt);
            }
        });
        getContentPane().add(btnRead, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 280, 150, 40));

        chkHex.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        chkHex.setText("Hex");
        chkHex.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(chkHex, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 290, -1, -1));

        lblFunction.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        lblFunction.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        lblFunction.setText("Function Error");
        getContentPane().add(lblFunction, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 340, 140, 20));

        txtFErrorCode.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        txtFErrorCode.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFErrorCode.setText(" ");
        getContentPane().add(txtFErrorCode, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 340, 80, 20));

        txtFErrorExplain.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N
        txtFErrorExplain.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFErrorExplain.setText(" ");
        getContentPane().add(txtFErrorExplain, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 340, 340, 20));

        btnGroup1.add(rbAUTH1A);
        rbAUTH1A.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        rbAUTH1A.setSelected(true);
        rbAUTH1A.setText("AUTH 1A");
        getContentPane().add(rbAUTH1A, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 280, -1, -1));

        btnGroup1.add(rbAUTH1B);
        rbAUTH1B.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        rbAUTH1B.setText("AUTH 1B");
        getContentPane().add(rbAUTH1B, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 300, -1, -1));

        lblKeyIndex.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        lblKeyIndex.setText("Key Index");
        getContentPane().add(lblKeyIndex, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 280, -1, -1));

        cboKeyIndex.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));
        cboKeyIndex.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        getContentPane().add(cboKeyIndex, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 300, -1, -1));

        pBar.setEnabled(false);
        getContentPane().add(pBar, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 320, 150, -1));

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

   private  Declarations.DLCARDTYPE DDT;
   private  MAX_SECTORS_PAGES_VALUE MSP;
   frmMain M;
    //max block in card 
    private int MaxBlock(int bTypeCard) {
        int iResult = 0;

        if (bTypeCard == DDT.DL_MIFARE_CLASSIC_1K.getValue()) {
            iResult = (MSP.MAX_SECTORS_1k.getValue() * 4);
        } else if (bTypeCard == DDT.DL_MIFARE_CLASSIC_4K.getValue()) {
            iResult = ((MSP.MAX_SECTORS_1k.getValue() * 2) * 4) + ((MSP.MAX_SECTORS_1k.getValue() - 8) * 16);
        } else if (bTypeCard == DDT.DL_MIFARE_ULTRALIGHT.getValue()) {
            iResult = MSP.MAX_PAGE_ULTRALIGHT.getValue();
        } else if (bTypeCard == DDT.DL_MIFARE_ULTRALIGHT_C.getValue()) {
            iResult = MSP.MAX_PAGE_ULTRALIGHT_C.getValue();
        } else if (bTypeCard == DDT.DL_NTAG_203.getValue()) {
            iResult = MSP.MAX_PAGE_NTAG203.getValue();
        }
        return iResult;
    }

    // private int iMaxBlock = MaxBlock(new frmMain().bTypeOfCard);
    private int maxBlock;
    private int result;
    private javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
    private JTable tblViewAll;
    private TableColumn column = null;
    private ExecutorService exec;
    
       
    private class NTAG1k4kTable   extends Thread 
    {
        private String cardFunction;
        NTAG1k4kTable(String card){
            cardFunction=card;         
        }
         @Override
         public void run()
         {             
                        M.SetFunct(true); 
                        if (cardFunction=="NTAG")                                                        
                              DrawNTAGGridTable();                                 
                        else
                             if (cardFunction=="1k4k")
                                 Draw1k4kGridValue();
                        M.SetFunct(false);
         }
    }
    
    private void DrawNTAGGridTable() {
      
           
            byte authMode = (rbAUTH1A.isSelected() ? MIFARE_AUTHENT1A : MIFARE_AUTHENT1B);
            byte keyIndex = (byte) cboKeyIndex.getSelectedIndex();
            byte[] blockRead = new byte[16];
            maxBlock =MaxBlock( M.bTypeOfCard);

            String data[][] = new String[maxBlock-3][5];
            String col[] = {"PAGE", "1", "2", "3", "4"};

            DefaultTableModel model = new DefaultTableModel(data, col);
            //tblViewAll = new JTable(model);
             tblViewAll.setModel(model);

            DefaultTableCellRenderer r = new DefaultTableCellRenderer();
            r.setBackground(Color.LIGHT_GRAY);
            r.setFont(new Font("Verdana", 1, 11));

            tblViewAll.getColumnModel().getColumn(0).setCellRenderer(r);
            tblViewAll.getColumnModel().getColumn(0).setWidth(2);

            for (int br = 1; br < 5; br++) {
                column = tblViewAll.getColumnModel().getColumn(br);
                column.setPreferredWidth(10);
            }

            jScrollPane1.setViewportView(tblViewAll);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 535, 270));
            pack();
            
            pBar.setVisible(true);
            pBar.setMaximum(maxBlock);                                    
            for (int rbr = 4; rbr <= maxBlock; rbr++) 
            {
                result = Declarations.UFrDeclarations.UFRInstance.BlockRead(blockRead, (short)rbr, authMode, keyIndex);                
                tblViewAll.setValueAt(rbr , rbr-4, 0);
                pBar.setValue(rbr);
                if (chkHex.isSelected()) {
                        for (int cbr = 0; cbr < 4; cbr++) {
                            tblViewAll.setValueAt("$" + Integer.toHexString(((char) blockRead[cbr] & 0xFF)), rbr-4, cbr+1);
                        }
                    } else {
                        for (int cbr = 0; cbr < 4; cbr++) {
                            tblViewAll.setValueAt((char) ((char) blockRead[cbr] & 0xFF), rbr-4, cbr+1 );
                        }
                    }
            }
            if (result==DL_OK){
                    Declarations.UFrDeclarations.UFRInstance.ReaderUISignal(FUNCT_LIGHT_OK, FUNCT_SOUND_OK);
                    M.SetStatusBar(txtFErrorCode, txtFErrorExplain, result);                    
                } 
            
            else {
                    Declarations.UFrDeclarations.UFRInstance.ReaderUISignal(FUNCT_LIGHT_ERROR, FUNCT_SOUND_ERROR);
                    M.SetStatusBar(txtFErrorCode, txtFErrorExplain, result);
                }
          pBar.setVisible(false);
    }

    private void Draw1k4kGridValue() {
      
            int iFResult = 0;
            byte auth_mode = (rbAUTH1A.isSelected() ? MIFARE_AUTHENT1A : MIFARE_AUTHENT1B);
            byte key_index = (byte) cboKeyIndex.getSelectedIndex();
            byte bBISCount = 0;
            byte bSectorCounter = 0;
            byte bBISCounter = 3;
            short shBlockCount = 0;
            byte[] baBlockRead = new byte[16];
            maxBlock = MaxBlock(M.bTypeOfCard);

            String data[][] = new String[maxBlock][19];
            String col[] = {"SCT", "BIS", "BLO", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"};

            DefaultTableModel model = new DefaultTableModel(data, col);
            tblViewAll.setModel(model);

            DefaultTableCellRenderer r = new DefaultTableCellRenderer();
            r.setBackground(Color.LIGHT_GRAY);
            r.setFont(new Font("Verdana", 1, 11));

            for (int br = 0; br < 3; br++) {
                tblViewAll.getColumnModel().getColumn(br).setCellRenderer(r);
                tblViewAll.getColumnModel().getColumn(br).setWidth(7);
            }

            for (int br = 3; br < 19; br++) {
                column = tblViewAll.getColumnModel().getColumn(br);
                column.setPreferredWidth(42);
                column.setHeaderValue(br - 3);
            }
           
            jScrollPane1.setViewportView(tblViewAll);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 535, 270));
            pack();
            
            pBar.setVisible(true);
            pBar.setMaximum(maxBlock);  
            
            while (shBlockCount < maxBlock) {
                bBISCount = 0;
                while (bBISCount < bBISCounter) {
                    tblViewAll.setValueAt(bSectorCounter, shBlockCount, 0);
                    tblViewAll.setValueAt(bBISCount, shBlockCount, 1);
                    tblViewAll.setValueAt(shBlockCount, shBlockCount, 2);

                    iFResult = Declarations.UFrDeclarations.UFRInstance.BlockRead(baBlockRead, shBlockCount, auth_mode, key_index);

                    for (int br = 0; br < 15; br++) {
                        if (chkHex.isSelected()) {
                            tblViewAll.setValueAt("$" + Integer.toHexString(((char) baBlockRead[br] & 0xFF)), shBlockCount, br + 3);

                        } else {
                            tblViewAll.setValueAt((char) ((char) baBlockRead[br] & 0xFF), shBlockCount, br + 3);
                        }

                    }
                    bBISCount++;
                    shBlockCount++;
                }

                for (int br = 0; br < 19; br++) {
                    tblViewAll.setValueAt("XXX", shBlockCount, br);
                }
                shBlockCount++;
                 pBar.setValue(shBlockCount);
                if (bSectorCounter >= 31 && shBlockCount % 16 == 0) {
                    bSectorCounter++;
                    bBISCounter = 15;
                } else {
                    bSectorCounter++;
                }
            }

            if (iFResult == DL_OK) {
                Declarations.UFrDeclarations.UFRInstance.ReaderUISignal(FUNCT_LIGHT_OK, FUNCT_SOUND_OK);
                M.SetStatusBar(txtFErrorCode, txtFErrorExplain, iFResult);
            } else {
                Declarations.UFrDeclarations.UFRInstance.ReaderUISignal(FUNCT_LIGHT_ERROR, FUNCT_SOUND_ERROR);
                M.SetStatusBar(txtFErrorCode, txtFErrorExplain, iFResult);
            }
            pBar.setVisible(false);
       
    }


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

            
                if (M.GetFunct() || M.GetLoop()) {
                    return;
                }                               
                if (M.bTypeOfCard == DDT.DL_MIFARE_ULTRALIGHT.getValue() || M.bTypeOfCard == DDT.DL_MIFARE_ULTRALIGHT_C.getValue()
                        || M.bTypeOfCard == DDT.DL_NTAG_203.getValue()) 
                {                       
                    exec=Executors.newCachedThreadPool();
                    exec.execute(new NTAG1k4kTable("NTAG"));                                                                                
                } else if (M.bTypeOfCard == DDT.DL_MIFARE_CLASSIC_4K.getValue() || M.bTypeOfCard==DDT.DL_MIFARE_CLASSIC_4K.getValue())                   
                {
                    exec=Executors.newCachedThreadPool();
                    exec.execute(new NTAG1k4kTable("1k4k"));
                }           
    }//GEN-LAST:event_btnReadActionPerformed

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated


    }//GEN-LAST:event_formInternalFrameActivated

    private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged

    }//GEN-LAST:event_formMouseDragged

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        
        String data[][] = new String[0][19];
        String col[] = {"SCT", "BIS", "BLO", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"};

        DefaultTableModel model = new DefaultTableModel(data, col);
        tblViewAll = new JTable(model);

        tblViewAll.getTableHeader().setBackground(Color.LIGHT_GRAY);
        tblViewAll.getTableHeader().setFont(new Font("Verdana", 1, 11));

        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setBackground(Color.LIGHT_GRAY);
        r.setFont(new Font("Verdana", 1, 11));

        for (int br = 0; br < 3; br++) {
            tblViewAll.getColumnModel().getColumn(br).setCellRenderer(r);
            tblViewAll.getColumnModel().getColumn(br).setWidth(7);
        }

        for (int br = 3; br < 19; br++) {
            column = tblViewAll.getColumnModel().getColumn(br);
            column.setPreferredWidth(42);
            column.setHeaderValue(br - 3);
        }
       
        pBar.setVisible(false);
        this.setLocation(11,9);

    }//GEN-LAST:event_formInternalFrameOpened

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup btnGroup1;
    private javax.swing.JButton btnRead;
    private javax.swing.JComboBox cboKeyIndex;
    private javax.swing.JCheckBox chkHex;
    private javax.swing.JTextField lblFunction;
    private javax.swing.JLabel lblKeyIndex;
    private javax.swing.JProgressBar pBar;
    private javax.swing.JRadioButton rbAUTH1A;
    private javax.swing.JRadioButton rbAUTH1B;
    private javax.swing.JTextField txtFErrorCode;
    private javax.swing.JTextField txtFErrorExplain;
    // End of variables declaration//GEN-END:variables
}
