package icsDyn;

import icsTables.ICSDIMMOCTableModel;
import icsTables.ICSGeneralTableModel;
import icsTables.ICSMOCAttributeTableModel;
import icsTables.ICSMOCBehaviourTableModel;
import icsTables.ICSMOCNotificationTableModel;
import icsTables.ICSServiceTableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.EventListener;
import java.util.Vector;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import org.w3c.dom.Document;
import pdfReport.PDFFileFilter;
import pdfReport.PDFReport;
import pdfReport.ReportPropertiesSelectionDialog;
import transport.ICSTransportTableModel;
import transport.TransportICS;
import transport.TransportProfile;
import transport.TransportTableModel;
import com.lowagie.text.Chapter;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import modifyIcs.ICSDocuments;

/**
 * This class represents the application menu bar
 * @author MC
 *
 */
public class MenuBarManager implements ActionListener, EventListener{
	ManagementView parent;
	 private JMenuBar menuBar;
	 private JMenu menuApp;
	 //private JMenu menuHelp;
	 private JMenuItem menuAppItemRestart;
	 private JMenuItem menuAppItemQuit;
	 private JMenuItem menuAppItemExportPdf;
	 private JMenuItem menuHelpItemAbout;
	 ReportPropertiesSelectionDialog dialog = null;
	 
	 public MenuBarManager(ManagementView parentIn){
		 parent= parentIn;
		 
//		Create menu bar
         
        menuBar = new JMenuBar();
        menuApp = new JMenu("Project");
        menuApp.setMnemonic(KeyEvent.VK_A);
        menuBar.add(menuApp);
        
        menuAppItemRestart = new JMenuItem("New", KeyEvent.VK_R);
        menuAppItemRestart.addActionListener(this);
        menuApp.add(menuAppItemRestart);
        
        menuAppItemQuit = new JMenuItem("Quit", KeyEvent.VK_Q);
        menuAppItemQuit.addActionListener(this);
        menuApp.add(menuAppItemQuit);
        
        menuAppItemExportPdf = new JMenuItem("Export PDF Report...", KeyEvent.VK_E);
        menuAppItemExportPdf.addActionListener(this);
        menuAppItemExportPdf.addMouseListener(new MouseAdapter(){

			public void mousePressed(MouseEvent arg0) {
				try {
					showExportOptionsDialog(arg0);
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
        	
        });
        menuApp.add(menuAppItemExportPdf);
        
//        menuHelp = 	new	JMenu("Help");
//        menuBar.add(menuHelp);
        
        menuHelpItemAbout = new JMenuItem("About ICSGenerator");
        menuHelpItemAbout.addActionListener(this);
        
        menuApp.add(menuHelpItemAbout);
//        menuHelp.add(menuHelpItemAbout);
                		 
	 }

	public void actionPerformed(ActionEvent arg0) {
		if(arg0.getSource() == menuAppItemQuit){
			System.exit(0);
		}
		if(arg0.getSource() == menuAppItemRestart){
			parent.init();
		}
		if(arg0.getSource() == menuHelpItemAbout){
			showAboutDialog();
		}
	}	

	private void showAboutDialog() {
		JFrame frame = new JFrame("About ICSGenerator");
		JDialog dialog = new AboutDialog(parent, frame);
		dialog.pack();
		dialog.setVisible(true);
		
		
	}

	public JMenuBar getMenuBar(){
		return menuBar;
	}
	private void export(File selFile, boolean[] isSelected) throws DocumentException, IOException{
		ICSDocuments icsDocs = parent.icsDocs;
		
		PDFReport report = new PDFReport(selFile);
		com.lowagie.text.Document document = report.doc;
		
		report.addTitle();
		
		Chapter chapter;
		if(isSelected[0]){
			chapter = report.createChapter("UML Diagram", null);
			document.add(chapter);
			report.addImage(parent.viewDrawing.getImage());
		}
		if(isSelected[1]){
			
			ICSGeneralTableModel generalTable = new ICSGeneralTableModel();
						
			chapter = report.createChapter(generalTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(generalTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromTaleModel(parent.viewGeneral.getTableModel()));
		}
		
		if(isSelected[2]){
			
			ICSServiceTableModel serviceTable = new ICSServiceTableModel();
						
			chapter = report.createChapter(serviceTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(serviceTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromTaleModel(parent.viewService.getTableModel()));
		}
		
		Document doc = icsDocs.getDoc(); 
		if(isSelected[3]){						
			ICSDIMMOCTableModel mocDimTable = new ICSDIMMOCTableModel(doc);
			chapter = report.createChapter(mocDimTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(mocDimTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromHtmlTable(mocDimTable.getResultTransformation()));
		}
		
		if(isSelected[4]){						
			ICSMOCAttributeTableModel mocAttrTable = new ICSMOCAttributeTableModel(doc);
			chapter = report.createChapter(mocAttrTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(mocAttrTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromHtmlTable(mocAttrTable.getResultTransformation()));
		}
		if(isSelected[5]){
			ICSMOCBehaviourTableModel mocBehavTable = new ICSMOCBehaviourTableModel(doc);
			chapter = report.createChapter(mocBehavTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(mocBehavTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromHtmlTable(mocBehavTable.getResultTransformation()));
		}
		if(isSelected[6]){
			ICSMOCNotificationTableModel mocNotifTable = new ICSMOCNotificationTableModel(doc);
			chapter = report.createChapter(mocNotifTable.getStrTitle() + "\n\n",new Paragraph(new Phrase(mocNotifTable.getStrDescription()+"\n\n")));
			document.add(chapter);
			document.add(report.createTableFromHtmlTable(mocNotifTable.getResultTransformation()));		
		}
		Vector<TransportProfile> vectProfiles = parent.viewTransport.getProfilesList();
		if(isSelected[7]){
			ICSTransportTableModel transport = new ICSTransportTableModel();
			
			chapter = report.createChapter(transport.getStrTitle()+"" + "\n\n",new Paragraph(new Phrase(transport.getStrDescription()+"\n\n")));
			for(int p = 0; p < vectProfiles.size(); p++){
				TransportProfile profile = (TransportProfile) vectProfiles.get(p);
				Vector<TransportICS> vectICS = profile.getTransportIcsList();
				for(int i = 0; i < vectICS.size(); i++){
					TransportICS ics = (TransportICS) vectICS.get(i);
					TransportTableModel model = new TransportTableModel(ics.getRoot());
					report.addSection(ics.getName()+"\n\n", null);
					chapter.add(report.getTableFromTreeTableModel(model));
				}
			}
			document.add(chapter);
		}
		report.close();
	}
	private File showExportDialog()
    {
		File selFile = null;
        JFileChooser chooser = new javax.swing.JFileChooser();
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        chooser.setCurrentDirectory(new File("../xml"));
        chooser.setFileFilter(new PDFFileFilter());
        int returnVal = chooser.showSaveDialog(parent);
        
        if( returnVal == JFileChooser.APPROVE_OPTION)
        {
        try{
                boolean save = true;
                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)
                {
                    selFile = null;
                }
            }
            catch(Exception e)
            {
                e.printStackTrace();
                selFile = null;
            }
        }      
        return selFile;
    }
	
	private void showExportOptionsDialog(MouseEvent e) throws DocumentException, IOException{
		boolean[] isEnable = new boolean[5];
		ICSDocuments icsDocs = parent.icsDocs;
		
		for(int i = 0; i < isEnable.length; i++)
			isEnable[i] = true;
		if(!parent.viewDrawing.isSelected())
			isEnable[0] = false;
		if(icsDocs.getDocGeneral() == null)
			isEnable[1] = false;
		if(icsDocs.getDocService() == null)
			isEnable[2] = false;
		if(icsDocs.getDoc() == null)
			isEnable[3] = false;
		Vector<TransportProfile> vectProfiles = parent.viewTransport.getProfilesList();
		if(vectProfiles == null || vectProfiles.size() == 0)
			isEnable[4] = false;
		
		if(dialog == null)
			dialog = new ReportPropertiesSelectionDialog(new JFrame(), isEnable);
		else{
			dialog.init();
			dialog.setDisableButtons(isEnable);
		}
		
		// set position relative to click coordinates
		dialog.setLocation(e.getX() + menuAppItemExportPdf.getX() + parent.getX(), e.getY()+ menuAppItemExportPdf.getY() + parent.getY());
		dialog.pack();
		dialog.setVisible(true);
		if(dialog.isOkBtnPressed()){
			File file = showExportDialog();
			boolean[] isSelected = dialog.getSelection();
			boolean noSel = true;
			for(int i = 0; i < isSelected.length; i++)
				if(isSelected[i]){
					noSel = false;
					i = isSelected.length;
				}
			if(file != null && !noSel){
				export(file, isSelected);				
			}			
		}
		
	}

}
