package smart_gs.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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 jp.ac.nii.hcp.client.core.ProjectEditor;
import jp.ac.nii.hcp.client.shared.HCPClientException;
import jp.ac.nii.hcp.shared.model.HCPProject;

import org.w3c.dom.Document;

import smart_gs.dictionary.DictionaryXML;
import smart_gs.network.ProjectHandler;

public class ProjectSaver {
	private HCPProject project;
	private Document document;

	public ProjectSaver(HCPProject project, Document xmlDocument) {
		this.project = project;
		this.document = xmlDocument;
	}

	public synchronized void save() {
		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;
            ProjectHandler.getInstance().editDocument(this.project, newstring);


			transformer = null;
			source = null;
		} catch (TransformerConfigurationException e1) {
			e1.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (HCPClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		factory = null;
	}


}
