package org.jivesoftware.spark.plugin.otr.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.log.Log;

/**
 * OTRProperties file stuff
 * 
 * @author Bergunde Holger
 */
public class OTRProperties {
    private final Properties props;

    private static final Object LOCK = new Object();
    private static OTRProperties instance = null;

    /**
     * returns the Instance of this Properties file
     */
    public static OTRProperties getInstance() {
        synchronized (LOCK) {
            if (instance == null) {
                instance = new OTRProperties();
            }
            return instance;
        }
    }

    private OTRProperties() {
        this.props = new Properties();
        try {
            props.load(new FileInputStream(getConfigFile()));
        } catch (IOException ignored) {
        }
    }

    private File getConfigFile() {
        return new File(SparkManager.getUserDirectory(), "otr.properties");
    }

    public void save() {
        try {
            props.store(new FileOutputStream(getConfigFile()), null);
        } catch (Exception e) {
            Log.error(e);
        }
    }

    public boolean getIsOTREnabled() {
        return getBoolean("isOTREnabeld", true);
    }

    public void setIsOTREnabled(boolean enabled) {
        setBoolean("isOTREnabeld", enabled);
    }

    public boolean getOTRCloseOnDisconnect() {
        return getBoolean("OTRCloseOnDisc", true);
    }

    public void setOTRCloseOnDisconnect(boolean enabled) {
        setBoolean("OTRCloseOnDisc", enabled);
    }

    public boolean getOTRCloseOnChatClose() {
        return getBoolean("OTRCloseOnChatClose", false);
    }

    public void setOTRCloseOnChatClose(boolean enabled) {
        setBoolean("OTRCloseOnChatClose", enabled);
    }

    private boolean getBoolean(String property, boolean defaultValue) {
        return Boolean.parseBoolean(props.getProperty(property, Boolean.toString(defaultValue)));
    }

    private void setBoolean(String property, boolean value) {
        props.setProperty(property, Boolean.toString(value));
    }

    private int getInt(String property) {
        return Integer.parseInt(props.getProperty(property, "0"));
    }

    private void setInt(String property, int integer) {
        props.setProperty(property, "" + integer);
    }

    public String getProperty(String property) {
        return props.getProperty(property);
    }

}
