package hsr.dsa.local;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertiesManager {
	private static final Logger log = LoggerFactory.getLogger(PropertiesManager.class);
	private static final File propertiesFile = new File("config.properties");
	private static PropertiesManager manager;
	
	private final Properties properties;
	
	private PropertiesManager() {
		this.properties = this.loadProperties();
	}

	public static PropertiesManager getPropertiesManager() {
		if(PropertiesManager.manager == null) {
			PropertiesManager.manager = new PropertiesManager();
		}
		return PropertiesManager.manager;
	}
	
	public synchronized String getProperty(String key) {
		return this.properties.getProperty(key, null);
	}
	
	public synchronized void setProperty(String key, String value) {
		this.properties.setProperty(key, value);
		this.saveProperties();
	}

	private void saveProperties() {
		try (OutputStream outputStream = new FileOutputStream(propertiesFile)) {
			this.properties.store(outputStream, null);
		} catch (IOException e) {
			log.error("Error loading Properties", e);
		}
	}

	private Properties loadProperties() {
		if (propertiesFile.isFile()) {
			try (InputStream inputStream = new FileInputStream(propertiesFile)) {
				Properties prop = new Properties();
				prop.load(inputStream);
				return prop;
			} catch (IOException e) {
				log.error("Error loading Properties", e);
			}
		}
		Properties prop = new Properties();
		prop.setProperty("root.ip", "localhost");
		prop.setProperty("root.port", "4000");
		prop.setProperty("client.port", "4000");
		return prop;
	}
}
