/**
 * Class Editor.
 * Here is the 'boot' class of the rdf Editor's GUI.
 * Of course, it implements a main method which sets all the graphic
 * components to be added in the main frame, thanks to either JComponent
 * subclasses or custom classes that gather several elements.
 * The components are :
 * - The graphic statement (3 labelized comboboxes)
 * - The statement control buttons (4 buttons + an attribute table)
 * - The text area
 * - The file menu (+inner classes that implement the relative event listeners)
 * Moreover, it implements a static method createDom which returns a DOM tree
 * corresponding to the svg file given as a parameter.
 **/

package axsvg.edition;

import axsvg.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import fr.dyade.koala.dom.*;
import fr.dyade.koala.dom.util.*;
import org.w3c.dom.*;
import java.util.*;
import javax.swing.table.*;
import fr.dyade.koala.xml.util.*;
import org.apache.xml.serialize.*;

public class Editor {
    public static void main(String[] args) throws Exception {
        try {
            UIManager.setLookAndFeel(
                UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) { }
	
	int numberOfArgs = args.length;
	Document doc;
	
	//if one argument has been given in the command line, considers it as
	//the name of the svg file to be processed: calls createDom.
	if(numberOfArgs == 1) {
	    doc = Editor.createDom(args[0]);
	}
	// if no arguments has been given, it creates an empty Document,
	// in order to launch the init processes on such a document.
	else {
	    doc = new GenericDocument();
	    ((GenericDocument)doc).setNodeName("svg");
	    Element elt = doc.createElement("svg");
	    doc.appendChild(elt);
	}

       DocumentMixte docMixte = new DocumentMixte(doc);

       //Create the top-level container
       final JFrame frame = new JFrame("Editor");

       
       //Create a text area.
       final JTextArea textArea = new JTextArea(
		     "Statement meaning (click Check Statement button)");
       textArea.setEditable(false);
       textArea.setFont(new Font("Serif",Font.PLAIN, 16));
       textArea.setLineWrap(true);
       textArea.setWrapStyleWord(true);

       //Create the graphic statement
       final Xstatement xstatement = new Xstatement(docMixte);
       Component stContents = xstatement.createStatement();

       //Create the menu bar and file chooser.
       JMenuBar menuBar = new JMenuBar();
       JMenu fileMenu = new JMenu("File");
       final JFileChooser fc = new JFileChooser();
       fileMenu.setMnemonic(KeyEvent.VK_F);
       fileMenu.getAccessibleContext().setAccessibleDescription(
					   "save or load a document");
       menuBar.add(fileMenu);
       JMenuItem menuItemLoad = new JMenuItem("Open", KeyEvent.VK_O);
       fileMenu.add(menuItemLoad);
       menuItemLoad.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
		try {
		    int returnVal = fc.showOpenDialog(fc);
		    if (returnVal == JFileChooser.APPROVE_OPTION) {
			String path = fc.getSelectedFile().getPath();
			Document docu = Editor.createDom(path);
			DocumentMixte docuMixte = new DocumentMixte(docu);
			textArea.setText("");
			xstatement.reload(docuMixte);
			frame.pack();
		    }
		} catch(Exception ex) {
		    //prints out the exception that occurs when the
		    //svg file loaded has a bad format.
		    System.out.println(ex.toString());
		    textArea.setText(ex.toString());
		}
	    }
       });
       JMenuItem menuItemSave = new JMenuItem("Save", KeyEvent.VK_S);
       fileMenu.add(menuItemSave);
       menuItemSave.addActionListener(new ActionListener() {
	   public void actionPerformed(ActionEvent e) {
	       Document toBeSerialized = xstatement.docMixte.getGenerator();
	       try {
		   int returnVal = fc.showOpenDialog(fc);
		   if (returnVal == JFileChooser.APPROVE_OPTION) {
		       String path = fc.getSelectedFile().getPath();
		       //Serializes the DOMtree (ie write in the chosen
		       //file the corresponding XML code)
		       DOMSerializer serializer = new XMLSerializer(
			       new FileWriter(path), new OutputFormat());
		       serializer.serialize(toBeSerialized);
		   }
	       } catch(Exception serial) {
	       System.out.println(serial.toString());
	       }
	   }
       });
	       
       
       //create a scrollpane
       JScrollPane areaScrollPane = new JScrollPane(textArea);
       areaScrollPane.setVerticalScrollBarPolicy(
       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
       //areaScrollPane.setPreferredSize(new Dimension(300, 243));
       areaScrollPane.setBorder(
		BorderFactory.createCompoundBorder(
                BorderFactory.createCompoundBorder(
                                BorderFactory.createTitledBorder(
				 "Statement meaning (click Check Statement)"),
                                BorderFactory.createEmptyBorder(5,5,5,5)),
                areaScrollPane.getBorder()));

       //Create the statement command buttons
       StatementCommandButtons statementCommandButtons =
	   new StatementCommandButtons(xstatement, textArea);
       Component controlArea =
	   statementCommandButtons.createStatementCommandButtons();

       //Add all the contents
       frame.setJMenuBar(menuBar);
       frame.getContentPane().add(stContents, BorderLayout.NORTH);
       frame.getContentPane().add(areaScrollPane, BorderLayout.CENTER);
       frame.getContentPane().add(controlArea, BorderLayout.EAST);
       

       //Finish setting up the frame, and show it.
       frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
       });
       frame.pack();
       //Center Frame
       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
       int largeurEcran = screenSize.width;
       int hauteurEcran = screenSize.height;   
       int largeurFrame = frame.getSize().width;
       int hauteurFrame = frame.getSize().height;
       int posX = (largeurEcran-largeurFrame)/2;
       int posY = (hauteurEcran-hauteurFrame)/2;
       frame.setLocation(posX, posY);
       frame.setVisible(true);
    }

    private static Document createDom(String name) throws Exception {
	// Sets the sax parser property to use the xerces parser
	System.setProperty("org.xml.sax.driver",
			   "org.apache.xerces.parsers.SAXParser");
	System.setProperty("org.w3c.css.sac.parser",
			   "org.w3c.flute.parser.Parser");
	// Opens a 'doc.xml' file located in the current directory
	//String uri = new File(".").toURL().toString()+name;
	DOMImplementation impl=GenericDOMImplementation.getDOMImplementation();
	Document doc = new DocumentFactory(impl).createDocument(
"http://www.w3.org/TR/2000/03/WD-SVG-20000303/DTD/svg-20000303-stylable.dtd",
"svg",name);
	// The document can now be used through the DOM API.
	return(doc);
    }
}
