package semorg.conf;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * This class holds the configuration of the application and provides methods to
 * get and set some properties of the application.
 */
public class Configuration {

    /** Holds the configuration for the application at runtime. */
    private Properties huSemOrgProperties;

    /** The path to configuration file of the application. */
    private static final String huSemOrgConfFile = "conf/husemorg.properties";

    /**
     * Creates a {@link Configuration} object, which holds the configuration of
     * the application.
     */
    public Configuration() {
	this.huSemOrgProperties = new Properties();

	try {
	    FileInputStream confInFile = new FileInputStream(huSemOrgConfFile);
	    huSemOrgProperties.load(confInFile);

	} catch (FileNotFoundException e) {

	    System.err.println("Configuration file " + huSemOrgConfFile
		    + " was not found and will now be created.");
	    makeStdConfiguration();

	} catch (IOException e) {
	    System.err
		    .println("Loading of the configuration failed. An IO error occured.");
	    e.printStackTrace();
	}
    }

    /** Saves the current configuration to file. */
    private void saveConfiguration() {
	try {
	    FileOutputStream confInFile = new FileOutputStream(huSemOrgConfFile);

	    huSemOrgProperties
		    .store(confInFile,
			    "Note the language is set with ISO 639 standard.\nLast Change: ");
	} catch (IOException e) {
	    System.err
		    .println("Saving of the configuration failed. An IO error occured.");
	    e.printStackTrace();
	}
    }

    /** Creates the standard configuration of the application. */
    private void makeStdConfiguration() {
	huSemOrgProperties.setProperty("language", "en");
	huSemOrgProperties.setProperty("background", "back_en.png");
	huSemOrgProperties.setProperty("selectLanguage", "disabled");
	saveConfiguration();
    }

    /**
     * Sets the property defined by the given key to the given value.
     * 
     * Note that configuration gets directly written to the configuration file.
     * 
     * @param key
     *                identifier of the property to set
     * @param value
     *                new value of the property
     */
    public void setProperty(String key, String value) {
	huSemOrgProperties.setProperty(key, value);
	saveConfiguration();
    }

    /**
     * Returns for given key the corresponding value of a property.
     * 
     * @param key
     *                name of the property
     * 
     * @return value of the property as String or <tt>null</tt> if the
     *         property does not exist.
     */
    public String getProperty(String key) {
	return huSemOrgProperties.getProperty(key);
    }
}
