package smart_gs.menu.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.StringWriter;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import jp.ac.nii.hcp.client.shared.HCPClientException;
import jp.ac.nii.hcp.shared.model.HCPProject;
import smart_gs.network.ProjectHandler;
import smart_gs.swingui.WorkspaceWindow;

public class ExportProjectAsGSXActionListener implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent arg0) {
		WorkspaceWindow ww = WorkspaceWindow.getInstance();
		ww.getTabbedPane().save();
		Document document;
		try {
			document = ww.buildXMLDocument();
			TransformerFactory factory = TransformerFactory.newInstance();
			try {
				Transformer transformer = factory.newTransformer();
				transformer.setOutputProperty("encoding", "UTF-8");
				transformer.setOutputProperty("standalone", "yes");
				transformer.setOutputProperty("indent", "yes");

				DOMSource source = new DOMSource(document);
				StringWriter output = new StringWriter();
				transformer.transform(source, new StreamResult(output));
				String string = output.toString();
				int p = string.indexOf("?>") + 2;
				String former = string.substring(0, p);
				String latter = string.substring(p + 1);
				String newstring = former + "\n<!DOCTYPE rootElement>" + latter;
				//TODO create gsx file
				ww.saveXMLDocument(null, document)
;
				transformer = null;
				source = null;
			} catch (TransformerConfigurationException e1) {
				e1.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
			factory = null;
		} catch (ParserConfigurationException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}

	}

}
