import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import org.apache.log4j.Logger;
/**
 * window to manage jobs and launching stamping
 * @author 413
 *
 */
public class Run
{
	static Logger logger = Logger.getLogger(Run.class.getName());
	/**
	 * Starting
	 * @param args
	 */
	public static void main(String args[])
	{
		/*
		logger.debug("msg de debogage");
		logger.info("msg d'information");
		logger.warn("msg d'avertissement");
		logger.error("msg d'erreur");
		logger.fatal("msg d'erreur fatale");
		*/
		logger.info("démarrage du programme");
		
		


        
		ServiceConfig.load();
		ServiceController.init();
		while(true)
		{
			if(ServiceController.run())
			{
				//====================================GET XML FILES====================================================
				
				/*
				 * a filter to get only XML files
				 */
				FilenameFilter filterXML = new FilenameFilter()
				{
					public boolean accept(File arg0, String arg1)
					{
						return arg1.endsWith(".xml");
					}
				};
				//Loading XML files
				File folder = ServiceConfig.job;
				File[] children = folder.listFiles(filterXML);
				ArrayList<Job> l = new ArrayList<Job>(children.length);
				for(int i = 0; i < children.length; i++)
				{
					l.add(Job.load(children[i]));
				}
				if(l.isEmpty())
				{
					System.out.println("No job to execute");
				}
				else
				{
					//======================================start stamping ================================================================
					StampleProcess sp = new StampleProcess();
					//delete folder Image Files
					folder = ServiceConfig.image;
					children = folder.listFiles();
					for(int i = 0; i < children.length; i++)
					{
						children[i].delete();
					}
					folder = ServiceConfig.logs;
					children = folder.listFiles();
					for(int i = 0; i < children.length; i++)
					{
						children[i].delete();
					}
					for(int i = 0; i < l.size();i++)
					{
						//execute the stamping
						sp.processJob(l.get(i));
					}
					if(sp.isStop())
					{
						ServiceController.stop();
					}
					else
					{
						ServiceController.finish();
					}
				}
			}
			else
			{
				try
				{
					Thread.sleep(1000);
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			logger.info("arret du programme");
		}
	}
}
