import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DragSource;

import javax.swing.border.EmptyBorder;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;


import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.activation.ActivationDataFlavor;
import javax.activation.DataHandler;
import javax.imageio.ImageIO;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.List;
import java.awt.*;

import java.awt.*;
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.Statement;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;


// http://1bestcsharp.blogspot.com/2015/05/java-jtable-add-delete-update-row.html

public class jdialog010 extends JDialog 
{
	private boolean close_Jdialog = false;
		
	private String pathDatafile = "F:\\JAVA\\workspace\\SPLIT01\\file.dat";
	
	private DefaultTableModel model;
	private JTextField txtName;
	private JTextField txtEmail;
	private JTextField txtComments;
	
	boolean row_Is_Selected = false;
    int index;
	
	int line = 0;
	
	private JFileChooser myJFileChooser = new JFileChooser(new File(".")); 
	
	public jdialog010(JFrame f, boolean modal) 
	{
	       super(f, modal);
	       
	       // fermer la fenetre
	       addWindowListener(new java.awt.event.WindowAdapter() 
	       {
	           public void windowClosing(java.awt.event.WindowEvent e) 
	           {
	        	   dispose();
	           }
	       });
	      
	       init();
     
	}
  
	private void init()
	{
		  	setResizable( false );
		  	
			setBounds(100, 100, 926, 550);
			setTitle("Jtable et Progress bar...");
			getContentPane().setLayout(null);
	     	
			ImageIcon icon = null;
			icon = createImageIcon("resources/settings.png", "");
			setIconImage( icon.getImage() );
			
		
			/*******************/
			
			JLabel lblAdd = new JLabel("Add :");
			lblAdd.setBounds(48, 200, 46, 14);
			getContentPane().add(lblAdd);
			
			// Name
			txtName = new JTextField();
			txtName.setToolTipText("Name");
			txtName.setBounds(84, 200, 86, 20);
			getContentPane().add(txtName);
			
			// Email
			txtEmail = new JTextField();
			txtEmail.setToolTipText("Email");
			txtEmail.setBounds(180, 200, 161, 20);
			getContentPane().add(txtEmail);

			
			// Email
			txtComments = new JTextField();
			txtComments.setToolTipText("Comments");
			txtComments.setBounds(400, 200, 161, 20);
			getContentPane().add(txtComments);
			
			
			//JTable table = new JTable( new MyTableModel(pathDatafile) );
			
			JTable table = new JTable();
			
			// alterner une couleur pour la visualisation
			/*JTable table = new JTable()
			 {
	            @Override
	            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
	                Component comp = super.prepareRenderer(renderer, row, column);
	                comp.setBackground(row % 2 == 0 ? Color.white : Color.orange);
	                return comp;
	            }
	        };*/
			
			// row selection
	        table.setSelectionBackground(Color.red);
			
			
			JScrollPane scrollPane = new JScrollPane();
			scrollPane.setBounds(94, 39, 532, 159);
			getContentPane().add(scrollPane);
			scrollPane.setViewportView(table);
			
			table.setBackground(Color.LIGHT_GRAY);
	        table.setForeground(Color.black);
	        Font font = new Font("",1,22);
	        table.setFont(font);
	        table.setRowHeight(30);
	        
	        
	        
	        
	        //DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
			//centerRenderer.setHorizontalAlignment( JLabel.CENTER );
			//table.setDefaultRenderer(String.class, centerRenderer);
	        
			//table.setSelectionBackground(Color.BLACK);
	        //table.setSelectionForeground(Color.white);
	        
	        //table.setCellSelectionEnabled(false);
	        //table.setDragEnabled(true);
	        
			
			// Model for Table
			model = (DefaultTableModel)table.getModel();
			model.addColumn("No");
			model.addColumn("Name");
			model.addColumn("Email");
			model.addColumn("Comments");			
			
			// pour centrer la colonne 1
			DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
	        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
	        table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
	        
	        /*
	        table.addFocusListener(new FocusAdapter() 
	        {
	            @Override
	            public void focusLost(FocusEvent e) 
	            {
	            	 table.getSelectionModel().clearSelection(); 
	            	 System.out.println("Focus lost");
	               /* if (e.getOppositeComponent().getParent() != table) 
	                {
	                    //loseCellFocus();
	                	 table.getSelectionModel().clearSelection(); 
	                	 //table.getCellEditor().stopCellEditing();
	                	 //table.clearSelection();
	                	 System.out.println("Focus lost");
	                }*/
/*	            }
	        });
	        */
	        
	        
			// Save
			JButton btnAdd = new JButton("Add");
			btnAdd.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{

					if( txtName.getText().equals("") || txtName.getText().equals("") || txtName.getText().equals("")  ) 
					{
				    	  String message = String.format("Warning: Incomplete fields !.");
				          JOptionPane.showMessageDialog(table, message, "Message", JOptionPane.INFORMATION_MESSAGE);
					}
					else	
					{	
						// New Rows
						int nb_row = table.getRowCount();
						if(nb_row != 0)
						{
							line = nb_row ; 
						}
						
						model.addRow(new Object[0]);
						
						model.setValueAt(line + 1, line, 0);
						model.setValueAt(txtName.getText(), line, 1);
						model.setValueAt(txtEmail.getText(), line, 2);
						model.setValueAt(txtComments.getText(), line, 3);
						line = line + 1;
									
						// Reset Text Field
						txtName.setText("");
						txtEmail.setText("");
						txtComments.setText("");
					}
					
				}
			});
			btnAdd.setBounds(351, 360, 67, 23);
			getContentPane().add(btnAdd);
						
			
			JButton btnRemove = new JButton("Supprimer");
			btnRemove.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					int i = table.getSelectedRow();
					
	                if(i >= 0)
	                {
	                    // remove a row from jtable
	                    model.removeRow(i);
	                    line = 0;
	                }
	                else{
	                    System.out.println("Delete Error");
	                    line = 0;
	                }
	                
	                int rows = table.getRowCount();
					line = 1;
					for(int j = 0; j < rows ; j++)
					{
						model.setValueAt(line  , j, 0);
						line = line + 1;
						System.out.println("___: " + line);
					}
					// annule la précédente incrémzntation
					line = line - 1;
				}
			});

			btnRemove.setBounds(450, 360, 67, 23);
			getContentPane().add(btnRemove);
			
			/*********************************/
			// https://www.rgagnon.com/javadetails/java-0213.html
			JButton btnLoad = new JButton("Load");
			btnLoad.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					
					 JFileChooser chooser = new JFileChooser();
			    	 chooser.setDialogTitle("Choice file");
			    	 FileNameExtensionFilter filter = new FileNameExtensionFilter( "XML file", "xml" );
			    	 chooser.setFileFilter(filter);
			    	 
			    	 int returnVal = chooser.showOpenDialog(table);
			
			    	 if(returnVal == JFileChooser.APPROVE_OPTION) 
			    	 {
					
						//String filePath ="F:\\JAVA\\workspace\\SPLIT01\\xxxxtartuffe.dat";
						
						File selectedFile = chooser.getSelectedFile();
						
				        //File file = new File(filePath);
				        String aLine ;
				        
				        //String[] nameCol = new String[4];
				        String[] dataRow = new String[4];
				        
						try 
				    	{
							  DefaultTableModel model = (DefaultTableModel)table.getModel();
							
							  FileInputStream fin =  new FileInputStream(selectedFile);
				    	      BufferedReader br = new BufferedReader(new InputStreamReader(fin));
				    	      //StringTokenizer st1 =  new StringTokenizer(br.readLine(), "|");
				    	      //while(st1.hasMoreTokens())
				    	      //{	  
				    	      //	  nameCol[0] = st1.nextToken();
				    	      //	  nameCol[1] = st1.nextToken();
				    	      //	  nameCol[2] = st1.nextToken();
				    	      //	  //nameCol[3] = st1.nextToken();
				    	      //}    
				    	      //model.setColumnIdentifiers(nameCol);
				    	      
				    	      line = 0;
				    	      
				    	      while ((aLine = br.readLine()) != null) 
				    	      {  
				    	    	  StringTokenizer st2 =   new StringTokenizer(aLine, "|");
				    	    	  while(st2.hasMoreTokens())
				    	    	  {	  
				    	    		  line = line + 1;
				    	    		  dataRow[0] = Integer.toString(line);
				    	    		  dataRow[1] = st2.nextToken();
				    	    		  dataRow[2] = st2.nextToken();
				    	    		  dataRow[3] = st2.nextToken();
				    	    		  
				    	    		  model.addRow(dataRow);
				    	    	  }	  
				    	      }
				    	      
				    	      br.close();   
							
				    	}
				    	 
				    	catch (Exception ex) 
				    	{
				    		ex.printStackTrace();
				    	}
			    	 }	
				}
			});

			btnLoad.setBounds(351, 260, 67, 23);
			getContentPane().add(btnLoad);
			
			/**********************************/
			
			JButton btnSave = new JButton("Save");
			btnSave.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
			         
					JFileChooser fileChooser = new JFileChooser();
			    	fileChooser.setDialogTitle("Specify a file to save");   
			    	 
			    	fileChooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
			    	
			    	int userSelection = fileChooser.showSaveDialog(table);
			    	 
			    	if (userSelection == JFileChooser.APPROVE_OPTION) 
			    	{
			    	    File fileToSave = fileChooser.getSelectedFile();
			    	    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
					
				        //String filePath ="F:\\JAVA\\workspace\\SPLIT01\\xxxxtartuffe.dat";
				        // File file = new File(filePath);
				         String space = "";
			         
						 try 
						 {
					            FileWriter fw = new FileWriter(fileToSave);
					            BufferedWriter bw = new BufferedWriter(fw);
					            
					            //// pour le header
					            /*for (int col = 1; col < table.getColumnCount(); col++) 
					            {
					            	if( col < table.getColumnCount() -1)
					            	{
					            		space = "|";
					            	}
					            	else
					            	{
					            		space = "";
					            	}
					                bw.write(table.getColumnName(col)  + space);
					            }
				                bw.newLine();*/
	
					            
					            for(int i = 0; i < table.getRowCount(); i++)
					            {
					                for(int j = 1; j < table.getColumnCount(); j++)
					                {
					                	if( j < table.getColumnCount() -1)
						            	{
						            		space = "|";
						            	}
						            	else
						            	{
						            		space = "";
						            	}
					                	
					                    bw.write(table.getValueAt(i, j).toString() + space);
					                   
					                }
					                
					                if(i < table.getRowCount() - 1 )
					                {	
					                	bw.newLine();
					                }	
					            }
					            
					            bw.close();
					            fw.close();
					            
					     } 
						
						 catch (Exception ex) 
					     {
					    		ex.printStackTrace();
					     }
						
						/*for (int row = 0; row < table.getRowCount(); row++) 
						{
						    for (int col = 0; col < table.getColumnCount(); col++) 
						    {
						        System.out.println(table.getColumnName(col));
						        System.out.println(": ");
						        System.out.println(table.getValueAt(row, col));
						    }
						}*/
			    	}	 
				}
			});

			btnSave.setBounds(450, 260, 67, 23);
			getContentPane().add(btnSave);
			
			/*********************************/
			
			
			JButton btnUp = new JButton("Up");
			btnUp.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					if(row_Is_Selected == false)
			        {
			            model = (DefaultTableModel)table.getModel();
			            row_Is_Selected = true;
			        }
			        
					if(table.getRowCount() > 1)
					{
					
				        index = table.getSelectedRow();
				        if(index > 0)
				        {
				            // move rows from the index to index into the position index -1
				            model.moveRow(index, index, index - 1);
				            // set selection to the new position
				            table.setRowSelectionInterval(index - 1, index - 1);
				            
				            // renumerotation
					        int rows = table.getRowCount();
							line = 1;
							for(int j = 0; j < rows ; j++)
							{
								model.setValueAt(line  , j, 0);
								line = line + 1;
								System.out.println("___: " + line);
							}
							// annule la précédente incrémzntation
							line = line - 1;
				            
				        }
					}
			        
				}
			});

			btnUp.setBounds(850, 120, 67, 23);
			getContentPane().add(btnUp);
			
			JButton btnDown = new JButton("Down");
			btnDown.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					  if(row_Is_Selected == false)
				      {
				            model = (DefaultTableModel)table.getModel();
				            row_Is_Selected = true;
				      }
				        
					  if(table.getRowCount() > 1)
					  {
					      index = table.getSelectedRow();
					      if(index < model.getRowCount() - 1)
					      {
					            model.moveRow(index, index, index + 1);
					            table.setRowSelectionInterval(index + 1, index + 1);
					            
					            // renumerotation
						        int rows = table.getRowCount();
								line = 1;
								for(int j = 0; j < rows ; j++)
								{
									model.setValueAt(line  , j, 0);
									line = line + 1;
									System.out.println("___: " + line);
								}
								// annule la précédente incrémzntation
								line = line - 1;
					        }
					  }
				}
			});

			btnDown.setBounds(850, 160, 67, 23);
			getContentPane().add(btnDown);
			
			
			 table.addMouseListener(new MouseAdapter()
			 {
		        @Override
		        public void mouseClicked(MouseEvent e)
		        {
		        	System.out.println("Click dans la table ...");	
		        }
	        });
			
			/*******************/
		
			JButton btn_ok = new JButton("OK");
			btn_ok.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent arg0) 
				{
					close_Jdialog = false;
					System.out.println("Btn Cancel  \n");
					dispose();
				}
			});
			btn_ok.setBounds(135, 391, 89, 23);
			getContentPane().add(btn_ok);
	
			/*******************/
			
			JButton btn_cancel = new JButton("Cancel");
			btn_cancel.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					close_Jdialog = false;
					System.out.println("Btn Cancel  \n");
					dispose();
				}
			});
			btn_cancel.setBounds(359, 391, 89, 23);
			getContentPane().add(btn_cancel);
		
	}
    
		
	public ImageIcon createImageIcon(String path,  String description) 
	{
		URL imgURL = getClass().getResource(path);

		if (imgURL != null)
		{
  			return new ImageIcon(imgURL, description);
		} 
		else 
		{
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}
	
	
	class MyTableModel extends AbstractTableModel 
	{
		
		protected Vector data;
	    protected Vector columnNames;  
	    
	    public MyTableModel(String pathDatafile)
	    {
	    	loadDatas(pathDatafile);
	    }
	    
	    public void loadDatas(String pathDatafile)
	    {
	    	String aLine ;
	        data = new Vector();
	        columnNames = new Vector();
	        
	    	try 
	    	{
	    	      FileInputStream fin =  new FileInputStream(pathDatafile);
	    	      BufferedReader br = new BufferedReader(new InputStreamReader(fin));
	    	      // extract column names
	    	      StringTokenizer st1 =  new StringTokenizer(br.readLine(), "|");
	    	        while(st1.hasMoreTokens())
	    	          columnNames.addElement(st1.nextToken());
	    	      // extract data
	    	      while ((aLine = br.readLine()) != null) 
	    	      {  
	    	    	  StringTokenizer st2 =   new StringTokenizer(aLine, "|");
	    	    	  while(st2.hasMoreTokens())
	    	    		  data.addElement(st2.nextToken());
	    	      }
	    	      
	    	      br.close();  
	    	}
	    	 
	    	catch (Exception e) 
	    	{
	    		e.printStackTrace();
	    	}
	    	
	    }
	    
	    public int getColumnCount() 
	    {
	    	return columnNames.size();
	    }

	    public int getRowCount() 
	    {
	    	return data.size() / getColumnCount();
	    }

	    public String getColumnName(int columnIndex) 
	    {
	    	 String colName = "";

	    	 if (columnIndex <= getColumnCount())
	    	       colName = (String)columnNames.elementAt(columnIndex);

	    	 return colName;
	    }

	    public Object getValueAt(int rowIndex, int columnIndex) 
	    {
	    	return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
	    }

	   
	    public Class getColumnClass(int columnIndex) 
	    {
	    	return String.class;
	    }

	    public boolean isCellEditable(int row, int col) 
	    {
	    	return false;
	    }
	   
	    public void setValueAt(Object value, int rowIndex, int columnIndex) 
	    {
	      	 return;
	    }

	}
	
	
  
}


/****************************************************************************************/
// https://www.thaicreate.com/java/java-gui-example-jtable-checkbox.html

/*
//Header Font & Color
table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 12));
table.getTableHeader().setForeground(Color.blue);

//Column Width
table.getColumnModel().getColumn(0).setPreferredWidth(30); 
table.setForeground(Color.black); 

//Row Height
table.setRowHeight(20);

//Column Center
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
table.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

*/


//   table.getSelectionModel().clearSelection()   deselect row