package comparingDevices;

import icsDyn.ExtUtils;
import icsDyn.XMLFileFilter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;


/**
 * This class represents the panel where the user selects the devices to compare
 * @author MC
 *
 */
public class DeviceSelectionPanel extends JPanel implements ActionListener{
    private static final long serialVersionUID = 1L;
	private JButton btnAddDevice;
	private JPanel pnlDevicePath;
	private Vector<JButton> vectBtnBrowser;
	private Vector<JLabel> vectLblPath;
	private Vector<JButton> vectBtnRemove;
	private Vector<String> vectFileName;
	private Vector<JTextField> vectTxtField;
	private JButton btnCompare;
	private JButton btnExport;
	private int nbDevices;
	private String errors;
	private MVC mvc;
	public DeviceSelectionPanel()
	{
		super();
		mvc = null;
		nbDevices = 0;
		vectBtnBrowser = new Vector<JButton>();
		vectLblPath = new Vector<JLabel>();
		vectBtnRemove = new Vector<JButton>();
		vectFileName = new Vector<String>();
		vectTxtField = new Vector<JTextField>();
		initializeComponents();
		addBtnAddDevice();

	}
	public void setMVC(MVC mvcIn){
		mvc = mvcIn;
	}
	private void initializeComponents()
	{
		java.awt.GridBagConstraints gridBagConstraints;
		
		 setLayout(new BorderLayout(5,5));
		 setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Devices selection")));
		 
		 //define the button addDevice
		 btnAddDevice = new JButton("Add a device");
		 btnAddDevice.setBackground(new Color(204, 204, 255));
		 btnAddDevice.addActionListener(this);
		 
		 //define the button startCompare
		 btnCompare = new JButton("Compare devices");
		 btnCompare.setBackground(new Color(204,204,255));
		 btnCompare.addActionListener(this);
		 
//		define the button export report
		 btnExport = new JButton("Export comparison report...");
		 btnExport.setBackground(new Color(204,204,255));
		 btnExport.addActionListener(this);
		 btnExport.setEnabled(false);
         
         
         //define the panel where the user can input the device path
		 pnlDevicePath = new JPanel();
		 pnlDevicePath.setLayout(new BoxLayout(pnlDevicePath, BoxLayout.PAGE_AXIS));
	
		 
		 // make it scrollable
		 JScrollPane scrollPan = new JScrollPane(pnlDevicePath);
		 scrollPan.setLayout(new ScrollPaneLayout());
		 scrollPan.setBorder(BorderFactory.createEtchedBorder());
		 
         gridBagConstraints = new java.awt.GridBagConstraints();
         gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
         gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
         gridBagConstraints.weightx = 1.0;
         gridBagConstraints.weighty = 1.0;
         add(scrollPan, BorderLayout.CENTER);
                 
         
	}
	private void addBtnAddDevice()
	{
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
		panel.add(btnAddDevice);
        
        //add space
        panel.add(Box.createRigidArea(new Dimension(10,0)));
        
        //add btn start comparaison
        panel.add(btnCompare);
        
//      add space
        panel.add(Box.createRigidArea(new Dimension(10,0)));
        
//      add btn start comparaison
        panel.add(btnExport);
        
        add(panel, BorderLayout.PAGE_END);
        
	}
	private void addSelctionPanel(int index)
	{
		JPanel panelSelection = new JPanel();
		JButton btnBrowser = new JButton("Browser...");
		JButton btnRemove = new JButton("Remove");
		JLabel lblDevice = new JLabel("Device number "+index+": ");
		JTextField txtFPath = new JTextField();
		panelSelection.setLayout(new javax.swing.BoxLayout(panelSelection, BoxLayout.LINE_AXIS));
		panelSelection.setBorder(BorderFactory.createEmptyBorder(2,10,2,10));
		
		btnBrowser.setBackground(new Color(204, 204, 255));
		btnBrowser.addActionListener(this);
		
		btnRemove.setBackground(new Color(204,204,255));
		btnRemove.addActionListener(this);
		
		lblDevice.setSize(new java.awt.Dimension(110, 30));
        panelSelection.add(lblDevice);
        
        
        txtFPath.setPreferredSize(new java.awt.Dimension(300, 30));
        panelSelection.add(txtFPath);
        
        //to let space between buttons
        panelSelection.add(Box.createRigidArea(new Dimension(10, 0)));
        
        panelSelection.add(btnBrowser);
        // to let space between buttons
        panelSelection.add(Box.createRigidArea(new Dimension(10, 0)));
        panelSelection.add(btnRemove);
        
        panelSelection.setMaximumSize(new Dimension(550,30));
        panelSelection.setAlignmentX(LEFT_ALIGNMENT);
        pnlDevicePath.add(panelSelection);
        
        vectBtnBrowser.add(btnBrowser);       
        vectLblPath.add(lblDevice);
        vectBtnRemove.add(btnRemove);
        vectTxtField.add(txtFPath);
        
        //we must refresh the frame
        paintAll(this.getGraphics());
	
	}
	public static void main(String[] args) {
		
		 java.awt.EventQueue.invokeLater(new Runnable() {
	            public void run() {
	            	JFrame form = new JFrame();
	        		DeviceSelectionPanel device = new DeviceSelectionPanel();
	        		form.getContentPane().setLayout(new GridLayout());
	        		form.getContentPane().add(device);
	        		form.setSize(600,200);
	        		form.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
	                form.setVisible(true);
	            }
	        });
	}
	public void actionPerformed(ActionEvent arg0) {
		boolean found = false;
		int i;
		if(arg0.getSource() == btnAddDevice)
		{
			//removeBtnAddDevice();
			nbDevices++;
			addSelctionPanel(nbDevices);
			//addBtnAddDevice();
			
		}
		else if(arg0.getSource() == btnCompare)
		{
			//set Files Name
			setFilesName();
			//validate files
			if(areFilesValid())
			{
				//start comparaison
				if(mvc != null)
					(mvc).startComparaison();
			}
			else
			{
				//error message
				JOptionPane.showMessageDialog(this, errors,"Error!", JOptionPane.ERROR_MESSAGE);
			}
			
		}
		else if(arg0.getSource() == btnExport)
		{
			//export();
//			start comparaison
			if(mvc != null)
				(mvc).export();
		}
		else{ 
			i = 0;
			while(!found && i < vectBtnRemove.size()){
					if(arg0.getSource() == (JButton)vectBtnRemove.get(i))
					{
						pnlDevicePath.remove(((JButton)vectBtnRemove.get(i)).getParent());
						//to refresh the frame (the repaint method does not rearrange the components)
						pnlDevicePath.validate();
						pnlDevicePath.repaint();
						RemoveDevice(i);
						found = true;
					}
					else if(arg0.getSource() == (JButton)vectBtnBrowser.get(i))
					{
						selectDevicePath(i);
						found = true;
					}
					else if(arg0.getSource() == (JTextField)vectTxtField.get(i))
					{
						found = true;
					}
					else
						i++;
				}
			}
		
	}
	private void setFilesName() {
		vectFileName.removeAllElements();
		for(int i = 0; i<vectTxtField.size(); i++)
			vectFileName.add(((JTextField)vectTxtField.get(i)).getText());
		
	}
	private boolean areFilesValid() {
		boolean areValid = true;
		errors = "";
		//we need minimum of two devices
		if(vectFileName.size() < 2){
			errors += "The minimum of files to compare is two!\n";
			areValid = false;
		}
		for(int i = 0; i<vectFileName.size(); i++){
			String fileName = (String) vectFileName.get(i);
			//test all fields are filled
			if( fileName.equals("") || fileName == null)
			{
				areValid = false;
				errors += "The text field number "+(i+1)+" is empty!\n";
			}
			//test all files have xml extension 
			else if(!ExtUtils.getExtension(fileName).equals(ExtUtils.xml))
			{
				areValid = false;
				errors += fileName + " is invalid!\n";
			}
			//test all files exists
			else if(!(new File(fileName).exists()))
			{
				areValid = false;
				errors += fileName + " doesn't exist!\n";
			}
		}
		return areValid;
	}
	private void selectDevicePath(int index) {
		JFileChooser fc = new JFileChooser();
		// Set the chooser to accept only XML files.
		fc.addChoosableFileFilter(new XMLFileFilter());
		fc.setAcceptAllFileFilterUsed(false);
        fc.setCurrentDirectory(new File("..\\xml"));
		int returnVal = fc.showOpenDialog(this);
		File f = null;
		if(returnVal == JFileChooser.APPROVE_OPTION) 
		{
			f = fc.getSelectedFile();
			((JTextField)vectTxtField.get(index)).setText(f.getAbsolutePath());
	    }
	}
	private void RemoveDevice(int index){
		vectBtnBrowser.remove(index);
		vectBtnRemove.remove(index);
		vectLblPath.remove(index);
		vectTxtField.remove(index);
	}
	public Vector<String> getFilesName(){
		return vectFileName;
	}
	public void setExportEnable(boolean bool){
		btnExport.setEnabled(bool);
	}
	
	
	

}
