package com.libreecm.commonAPI.configuration;

import java.io.IOException; 

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.libreecm.commonAPI.auxiliars.XMLConverter;


public class ComponentConfig {
	private Config config;
	private static ComponentConfig componentConfig=null;
	private final String XML_FILE_NAME = "/etc/libreecm/config.xml";
	private XMLConverter converter;
	
	protected ComponentConfig() {

		 this.config=new Config();
		 ApplicationContext appContext =
		            new ClassPathXmlApplicationContext("/applicationContext.xml");
		        converter = (XMLConverter) appContext.getBean("XMLConverter");
		 load();
	}
	

	private static ComponentConfig get() {
		if (componentConfig == null) {
			componentConfig = new ComponentConfig();
		}
		return componentConfig;
	}	
	
	private void save() throws IOException{
		// from XML to object
		converter.convertFromObjectToXML(config, XML_FILE_NAME);	
	}
	
	private void load(){
		try {
			// from XML to object
			config = (Config) converter.convertFromXMLToObject(XML_FILE_NAME);
		} catch (Exception e){
			System.out.println("FAILED to load file "+XML_FILE_NAME+". Loading default configuration");
			try {
				save();
				} catch (IOException ex){
					System.out.println("Couldn't save configuration file "+XML_FILE_NAME);
				}
		}
	}

	
	public static void setConfig(Config config) throws IOException{
		get().config=config;
		get().save();
	}
   	
	public static Config getConfig(){
			return get().config;
	}
}
