
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 a job
 * @author 413
 *
 */
public class ServiceController 
{
	final static File file = ServiceConfig.controller;
	//XML elements
	static Element saveroot = new Element("root");
	static Element loadroot = new Element("root");
	static Element run = new Element("run");
	static Element finish = new Element("finish");
	static Element stop = new Element("stop");
	
	static org.jdom.Document saveDoc = new Document(saveroot);
	static org.jdom.Document loadDoc = new Document(loadroot);
	
	/**
	 * constructor
	 */
	public static void init()
	{
		saveroot.addContent(run);
		saveroot.addContent(finish);
		saveroot.addContent(stop);
	}

	/**
	 * save the job into a job.xml file
	 * @param job the job to save
	 */
	public void  run()
	{
		   try
		   {
			  run.setText("true");
			  finish.setText("false");
			  stop.setText("false");
			  //save data
		      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		      FileOutputStream out = new FileOutputStream(file);
		      sortie.output(saveDoc, out);
		      out.close();
		   }
		   catch (java.io.IOException e){System.out.println("an error occurred while saving the controller's file after finished");}
	}

	/**
	 * save the job into a job.xml file
	 * @param job the job to save
	 */
	public void  stop()
	{
		   try
		   {
			  run.setText("false");
			  finish.setText("false");
			  stop.setText("true");
			  //save data
		      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		      FileOutputStream out = new FileOutputStream(file);
		      sortie.output(saveDoc, out);
		      out.close();
		   }
		   catch (java.io.IOException e){System.out.println("an error occurred while saving the controller's file after finished");}
	}

	/**
	 * load the job from job.xml file
	 * @param source
	 * @return the job
	 */
	public Boolean isStop()
	{
		Boolean ret = false;
		SAXBuilder sxb = new SAXBuilder();
		try
		{
			org.jdom.Document loadDoc = sxb.build(file);
			Element rootload = loadDoc.getRootElement();
			ret = rootload.getChild("stop").getText().equals("true");
		}
		catch(Exception e)
		{
			System.out.println("an error occurred while loading the controller's file : "+e.getMessage());
		}
		return ret;

	}

	public boolean isFinish()
	{
		Boolean ret = false;
		SAXBuilder sxb = new SAXBuilder();
		try
		{
			org.jdom.Document loadDoc = sxb.build(file);
			Element rootload = loadDoc.getRootElement();
			ret = rootload.getChild("finish").getText().equals("true")||rootload.getChild("stop").getText().equals("true");
		}
		catch(Exception e)
		{
			System.out.println("an error occurred while loading the controller's file : "+e.getMessage());
		}
		return ret;
	}
}
