/**
 * Scott's XML Editor - Swing and JDOM XML Editor
 * @author Scott Hurring - scott at hurring dot com
 * @version beta1
 * @license GPL
 * For most recent version, go to this url:
 * http://hurring.com/code/java/xmleditor/
 */

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * ScottEditor application
 */
public class ScottEditor 
{
	public MainFrame mf;
	public XMLEditor xmleditor;
	public double VERSION = 1.0;
	
	// Currently opened file
	public File file;
	// The current XML Document
	public Document doc;
	
	public ScottEditor() {
		mf = new MainFrame(this);
		xmleditor = new XMLEditor(this);
		mf.setXMLEditor(xmleditor.createGUI());
		newFile();
	}
	
	/**
	 * Start a new document, clean up the Tree.
	 */
	public void newFile() {
		mf.setTitle("Untitled");
		mf.text.setText("");
		debug("New File");
		
		file = new File("");
		xmleditor.buildXMLDocument();
	}

	/**
	 * Show file chooser and open the selected XML file
	 */
	public void openFile() {
		JFileChooser fc = new JFileChooser();
		int r = fc.showOpenDialog(mf);
		if (r != JFileChooser.APPROVE_OPTION) {
			return ;
		}
		
		file = fc.getSelectedFile();
		debug("Open: "+ file.getAbsolutePath());
		mf.setTitle(file.getAbsolutePath());
		
		xmleditor.buildXMLDocument();
	}
	
	/**
	 * Save the current opened file back to disk.
	 * If no open file, show a file chooser.
	 */
	public void saveFile() {
		if (file.getName() == "") {	
			saveAs();
			return ;
		}
	
		XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());

		try {
			FileWriter os = new FileWriter(file);
			out.output(doc, os);
			debug("Saved: "+ file.getAbsolutePath());	
		} catch (IOException e) {
			debug("Error! "+ e.getMessage());
		}	
	}
	
	/**
	 * Show the save file chooser and save the file.
	 */
	public void saveAs() {
		JFileChooser fc = new JFileChooser();
		int r = fc.showSaveDialog(mf);
		if (r != JFileChooser.APPROVE_OPTION) {
			return ;
		}

		file = fc.getSelectedFile();
		saveFile();
	}

	public void showAboutDialog() {
		new AboutDialog().display();
	}
	
	public void performExitAction() {
		System.exit(0);
	}
	
	public void debug(String string) {
		mf.text.append(string +"\n");
	}
	
	public void debugClear() {
		mf.text.setText("");
	}

	/**
	 * Runs the program.
	 */
	public static void main(String[] args) 
	{
		try {
			//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception e) { }

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new ScottEditor();
			}
		});
	}

}

