import java.io.File;
import java.io.FileOutputStream;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * save or load config.xml file
 * @author 413
 *
 */
public class ServiceConfig
{

	final private static String file = "../config.xml";
	public static File controller;
	public static File source;
	public static File destination;
	public static File logs;
	public static File job;
	public static File stamp;
	public static File image;
	public static File result;

	/**
	 * save data into config.xml
	 * @param Pcontroller
	 * @param Psource
	 * @param Pdestination
	 * @param Plogs
	 * @param Pjob
	 * @param Pstamp
	 * @param Pimage
	 * @param Presult
	 */
	public static void save(File Pcontroller, File Psource, File Pdestination, File Plogs, File Pjob, File Pstamp, File Pimage, File Presult)
	{
		//XML elements
		Element Eroot = new Element("root");
		Element Econtroller = new Element("Controller");
		Element Esource = new Element("Source");
		Element Edestination = new Element("Destination");
		Element Elogs = new Element("Logs");
		Element Ejob = new Element("Job");
		Element Estamp = new Element("Stamp");
		Element Eimage = new Element("Image");
		Element Eresult = new Element("Result");
		
		Eroot.addContent(Econtroller);
		Eroot.addContent(Esource);
		Eroot.addContent(Edestination);
		Eroot.addContent(Elogs);
		Eroot.addContent(Ejob);
		Eroot.addContent(Estamp);
		Eroot.addContent(Eimage);
		Eroot.addContent(Eresult);

		Econtroller.setText(Pcontroller.getPath());
		Esource.setText(Psource.getPath());
		Edestination.setText(Pdestination.getPath());
		Elogs.setText(Plogs.getPath());
		Ejob.setText(Pjob.getPath());
		Eresult.setText(Presult.getPath());
		try
		{
			//save data
			org.jdom.Document Doc = new Document(Eroot);
			XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
			FileOutputStream out = new FileOutputStream(file);
			sortie.output(Doc, out);
			out.close();
		}
		catch (java.io.IOException e)
		{
			System.out.println("an error occurred while saving config.xml");
		}
	}

	/**
	 * load config.xml
	 */
	public static void load()
	{
		SAXBuilder sxb = new SAXBuilder();
		try
		{
			org.jdom.Document Doc = sxb.build(file);
			Element rootload = Doc.getRootElement();
			controller = new File(rootload.getChild("Controller").getText());
			source = new File(rootload.getChild("Source").getText());
			destination = new File(rootload.getChild("Destination").getText());
			logs = new File(rootload.getChild("Logs").getText());
			job = new File(rootload.getChild("Job").getText());
			stamp = new File(rootload.getChild("Stamp").getText());
			image = new File(rootload.getChild("Image").getText());
			result = new File(rootload.getChild("Result").getText());
		}
		catch(Exception e)
		{
			System.out.println("an error occurred while loading config.xml");
		}

	}
}
