/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
 */
package com.opcturkey.kepserverexdesktopclient;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import com.opencsv.exceptions.CsvValidationException;
import java.awt.List;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.commons.lang.ArrayUtils;

/**
 *
 * @author yunus
 */
public class MutlipleKepServerList extends javax.swing.JFrame {
ArrayList<String> CSVrowHolder = new ArrayList<>();
 String[] splittedOneRowArray ;
    private BufferedImage icon1;
    
    
   
    
    /**
     * Creates new form MutlipleKepServerList
     */
    public MutlipleKepServerList() {
        initComponents();
        
             try {
             this.icon1 = ImageIO.read(new File("C:\\Users\\yunus\\Documents\\NetBeansProjects\\KepServerExDesktopClient\\src\\main\\java\\com\\opcturkey\\kepserverexdesktopclient\\resources\\robotic-arm.png"));
             setIconImage(icon1);  } catch (IOException ex) {
             Logger.getLogger(loginCreditChangerDetails.class.getName()).log(Level.SEVERE, null, ex);
         }
    }

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

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Segoe UI Emoji", 0, 24)); // NOI18N
        jLabel1.setText("List of Configured Kepware Servers");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "IP and Port", "Username", "Password", "Give it a name"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setBackground(new java.awt.Color(102, 204, 0));
        jButton1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jButton1.setForeground(new java.awt.Color(0, 102, 102));
        jButton1.setText("Save");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setBackground(new java.awt.Color(255, 153, 153));
        jButton2.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jButton2.setText("+");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setBackground(new java.awt.Color(255, 204, 102));
        jButton3.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
        jButton3.setText("-");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jMenu1.setText("Options");

        jMenuItem1.setText("Don't Show Warning for Saving New Data");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Import Previously Saved");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("Usage Guide");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(300, 300, 300)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(421, 421, 421)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 14, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 965, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(15, 15, 15))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jLabel1)
                .addGap(34, 34, 34)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(32, 32, 32))
        );

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

    
    public void functionForBelow() throws IOException{
          
          jTable1.clearSelection();
         
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
   
     
    
    FileWriter csv= new FileWriter(new File("KepServerList.csv"));
    
    for(int i=0;i<model.getColumnCount();i++){
        
            csv.write(model.getColumnName(i)+",");
         
    }
    csv.write("\n");
    
    
    for(int i=0;i<model.getRowCount();i++){ 
        
        for(int a=0;a<model.getColumnCount();a++){
           
            if(model.getValueAt(i,a)!=null && model.getValueAt(i,a).toString().length()>0){
                
                 csv.write(model.getValueAt(i,a).toString()+",");
            }
            
           
            
        } csv.write("\n");
    }
    
    csv.close();
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    
        if(controlKepListSaveBtn==false){
              int writeIntoExcelConfirm =JOptionPane.showConfirmDialog(null,"You are about the REPLACE your datasheet of saved Kepware Server credentials with this one. Are you sure?","WARNING",JOptionPane.YES_NO_OPTION);
     
     if(writeIntoExcelConfirm==JOptionPane.YES_OPTION){
                 
        try {
           
               jTable1.editCellAt(1, 1);

            
                       

            functionForBelow();
            
             JOptionPane.showMessageDialog(null,"Operation completed.");
        } catch (IOException ex) {
            Logger.getLogger(MutlipleKepServerList.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null,"Operation failed.");
        }
     }else{
         JOptionPane.showMessageDialog(null,"Operation canceled safely."
                 + "");
         
     }
       
        }else{
            ///
     
                 
        try {
           
               jTable1.editCellAt(1, 1);

            
                       

            functionForBelow();
            
             JOptionPane.showMessageDialog(null,"Operation completed.");
        } catch (IOException ex) {
            Logger.getLogger(MutlipleKepServerList.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null,"Operation failed.");
        
     
         
     }catch(Exception e){
                      JOptionPane warningX = new JOptionPane("Ops! there is comething else wrong!");
                      warningX.setVisible(true);

     }
            ///
        }
        
      

    }//GEN-LAST:event_jButton1ActionPerformed
 boolean controlKepListSaveBtn=false;
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        if(controlKepListSaveBtn==false){
             
            jMenuItem1.setText("Show Warning when Saving New Data");
            
              controlKepListSaveBtn=true;
        }else{
            
              controlKepListSaveBtn=false;
                        jMenuItem1.setText("Don't Show Warning for Saving New Data");

        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try{
    

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.addRow(new Object[]{"","","",""});
      }catch(Exception e){
                      JOptionPane warningX = new JOptionPane("Ops! there is comething else wrong!");
                      warningX.setVisible(true);

     }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
       try{
           DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
      
        model.removeRow(model.getRowCount()-1);
         }catch(Exception e){
                      JOptionPane warningX = new JOptionPane("Ops! there is comething else wrong!");
                      warningX.setVisible(true);

     }
    }//GEN-LAST:event_jButton3ActionPerformed
       String[] arrayOfTheSplitted;
         String StringOfarrayOfElements;
    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed

       
         
 //"KepServerList.csv"
          try(CSVReader reader = new CSVReader(new FileReader("KepServerList.csv"))){
             
            var list= reader.readAll();
            
            list.remove(list.get(0));
            
            for(int i=0;i<list.size();i++){
                
               if(Arrays.toString(list.get(i)).contains(",")==false){
                   
                   list.remove(list.get(i));
               } 
               
               
                
            }
            
          DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                    
            list.forEach(each  -> System.out.println( 
                           
                    StringOfarrayOfElements=Arrays.toString(each)  ));
            
          Collections.reverse(list);
            Object object1; Object object2; Object object3; Object object4;
            
          for(int i=0; i < list.size(); i++){
              
              
              var oneRow= list.get(i);
              
               splittedOneRowArray = Arrays.toString(oneRow).split(",");
              
               object1=splittedOneRowArray[0].replace("[", "").replace("]","");
               object2=splittedOneRowArray[1].replace("[", "").replace("]","");
               object3=splittedOneRowArray[2].replace("[", "").replace("]","");
               object4=splittedOneRowArray[3].replace("[", "").replace("]","");
               
               model.insertRow(0,new Object[]{object1,object2,object3,object4});
          }
             
                
              
             
         } catch (FileNotFoundException ex) {
            Logger.getLogger(MutlipleKepServerList.class.getName()).log(Level.SEVERE, null, ex);
            
             JOptionPane warningX = new JOptionPane("Ops! You don't have any pre-saved configurations! Or you deleted a very important file!");warningX.setVisible(true);
        } 
          
          
          catch (IOException ex) {
            Logger.getLogger(MutlipleKepServerList.class.getName()).log(Level.SEVERE, null, ex);
             JOptionPane warningX = new JOptionPane("Ops! You don't have any pre-saved configurations! Or another error occured!");warningX.setVisible(true);
        }
          
          
          
          catch (CsvException ex) {
            Logger.getLogger(MutlipleKepServerList.class.getName()).log(Level.SEVERE, null, ex);
             JOptionPane warningX = new JOptionPane("Ops! You don't have any pre-saved configurations! Or there is comething else wrong!");warningX.setVisible(true);
        }
          
          
          catch(ArrayIndexOutOfBoundsException ae){
          JOptionPane warningX = new JOptionPane("Ops! You don't have any pre-saved configurations! Or there is comething else wrong because when we read, we only find empty fields!");
   warningX.setVisible(true);
              
        }
          
          catch(Exception e){
               JOptionPane warningX = new JOptionPane("Ops! You don't have any pre-saved configurations! Or there is comething else wrong because when we read, we only find empty fields!");
   warningX.setVisible(true);
          }
   
          
          
       
          
          
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        UsageGuideForMultipleIP guide = new UsageGuideForMultipleIP();
        guide.show();
    }//GEN-LAST:event_jMenuItem3ActionPerformed

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

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MutlipleKepServerList().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
