package comparingDevices;

import icsDyn.MVCArg;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import com.lowagie.text.DocumentException;


import pdfReport.PDFFileFilter;
import pdfReport.PDFReport;

/**
 * this class represents the view to compare devices
 * @author maria
 *
 */
public class comparaisonManagementView extends JPanel implements Observer{
    private static final long serialVersionUID = 1L;
	private DeviceSelectionPanel deviceSelPanel;
	private ComparaisonTable compTable;
	private JScrollPane scrollPan;
	private Vector<String> vectFileName;
	private CompareDevices compareDevicesObj;
	private MVC mvc;
	private JPopupMenu jmenu;
	private int selectedRow;
	private int viewNumber;
	public comparaisonManagementView(){
		super();
		initComponents();
		vectFileName = new Vector<String>();
		
		// set up the MVC model
		mvc = new MVC();
		mvc.addObserver(this);
		deviceSelPanel.setMVC(mvc);
		compTable.setMVC(mvc);
		
		
	}
	private void initComponents() {
		setLayout(new GridLayout());
		
		deviceSelPanel = new DeviceSelectionPanel();
		//deviceSelPanel.setPreferredSize(new Dimension(500,200));
		compTable = new ComparaisonTable();
				
		scrollPan = new JScrollPane(compTable);
		// mouse listner
		scrollPan.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent e) {
				if( viewNumber > 1)
				{
					jmenu.removeAll();
    				jmenu.add(new MenuItemAction("Back"));
    				jmenu.show(scrollPan, e.getPoint().x, e.getPoint().y);
    			}  			    
				
			}
		});
		
		JSplitPane splitPan = new JSplitPane(JSplitPane.VERTICAL_SPLIT, deviceSelPanel, scrollPan);
		deviceSelPanel.setMinimumSize(new Dimension(500, 200));
		scrollPan.setMinimumSize(new Dimension(500, 200));
		add(splitPan);
		
		jmenu = new JPopupMenu();
		
	}
	
	
	public static void main(String[] args) {		
		 java.awt.EventQueue.invokeLater(new Runnable() {
	            public void run() {
	            	JFrame form = new JFrame("Test of comparing devices");
	        		comparaisonManagementView view = new comparaisonManagementView();
	        		form.getContentPane().setLayout(new GridLayout());
	        		form.getContentPane().add(view);
	        		form.setSize(650,700);
	        		form.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
	                form.setVisible(true);
	            }
	        });
	}
	public void update(Observable o, Object arg) {
		if(o instanceof MVC) {	
        	if(arg instanceof MVCArg) {
        		if("start".equals(((MVCArg)arg).getName())) {
                    vectFileName = deviceSelPanel.getFilesName();
                    compareDevices();
                    viewNumber = 1;
                    deviceSelPanel.setExportEnable(true);
                }
        		else if("export".equals(((MVCArg)arg).getName())) {
                 export();
                    }
        	
        	 
        	
        		else if("select".equals(((MVCArg)arg).getName())) {
        			Integer row = (Integer)((MVCArg)arg).getOValue();
        	        selectedRow = row.intValue();
                }
        	
        	
        		else if("menu".equals(((MVCArg)arg).getName())) {
        			Point p = (Point)((MVCArg)arg).getOValue();
        			if(viewNumber == 1){
        				//init popup menu
        				jmenu.removeAll();
        				jmenu.add(new MenuItemAction("Attributes"));
        				jmenu.add(new MenuItemAction("Behaviours"));
        				jmenu.add(new MenuItemAction("Notifications"));
        			}
        			else{
        				jmenu.removeAll();
        				jmenu.add(new MenuItemAction("Back"));
        			}
        			jmenu.show(compTable, p.x, p.y);    			
        				
                }
        		
        	}
		}		
	}
	
	private void compareDevices() {
		compareDevicesObj = new CompareDevices(vectFileName);
		compareDevicesObj.compareMOC();
		compTable.setData(compareDevicesObj.megaDevice.vectMOC, compareDevicesObj.vectCompareMOC, vectFileName);
		scrollPan.setViewportView(compTable);
		validate();
	}
	
	private class MenuItemAction extends AbstractAction{
                private static final long serialVersionUID = 1L;
		String title;
		public MenuItemAction(String titleIn)
		{
			super(titleIn);
			title = titleIn;
			
		}

		public void actionPerformed(ActionEvent act) {
			if (title.equals("Attributes"))
			{
				compareDevicesObj.compareAttributes(selectedRow);
				compTable.setData(compareDevicesObj.getVectAttributes(selectedRow), compareDevicesObj.vectCompareAtt, vectFileName);
				viewNumber = 2;
			}
			else if(title.equals("Behaviours")){
				compareDevicesObj.compareBehaviours(selectedRow);
				compTable.setData(compareDevicesObj.getVectBehaviours(selectedRow), compareDevicesObj.vectCompareBehav, vectFileName);
				viewNumber = 3;
			}
			else if(title.equals("Notifications")){
				compareDevicesObj.compareNotifications(selectedRow);
				compTable.setData(compareDevicesObj.getVectNotifications(selectedRow), compareDevicesObj.vectCompareNotif, vectFileName);
				viewNumber = 4;
			}
			else if(title.equals("Back")){
				viewNumber = 1;
				compTable.setData(compareDevicesObj.megaDevice.vectMOC, compareDevicesObj.vectCompareMOC, vectFileName);
			}
		}
		
	}
	
	private boolean export()
    {
    	boolean ret = false;
        JFileChooser chooser = new javax.swing.JFileChooser();
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setCurrentDirectory(new File("../xml"));
        chooser.setFileFilter(new PDFFileFilter());
        int returnVal = chooser.showSaveDialog(this);
        if( returnVal == JFileChooser.APPROVE_OPTION)
        {
        try{
                boolean save = true;
                File selFile = chooser.getSelectedFile();
                if(!selFile.getPath().endsWith(".pdf"))
                {
                    selFile = new File(selFile.getPath() + ".pdf");
                }
                if(selFile.exists())
                {
                   save = false;     
                   returnVal = JOptionPane.showConfirmDialog(chooser, selFile.getAbsolutePath()+" already exists. Do you want to replace it?","Warning",JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                   if(returnVal == JOptionPane.OK_OPTION)
                       save = true;
                }
                if(save)
                {
                	savePDFReport(selFile);
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }      
        return ret;
    }
	private void savePDFReport(File selFile) throws DocumentException, IOException{
		
		PDFReport report = new PDFReport(selFile);
		compareDevicesObj.getPDFReport(report);
	}
}
