package backend;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;


public class Settings {
	
	/**
	 * Name for iTunes library file location
	 */
	public static final String ITUNES_LIBRARY = "library";
	
	/**
	 * Name for mobile library (directory) location
	 */
	public static final String MOBILE_LIBRARY_DIR = "mobile_library"; 
	
	
	public static final String LIBRARY_FILENAME = "lib_filename";
	public static final String SYNC_ENTIRE_LIBRARY = "sync_entire";
	public static final String SYNC_PLAYLIST_PREFIX = "playlist_sync_";
	
	public static final String CONFIGFILE_NAME = "config.cfg";
	
	private Map<String,String> settings;
	
	public Settings() {
		this.settings = new TreeMap<String,String>();
		this.setDefaults();
		
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				Settings.this.printSettingsToFile(new File(Settings.CONFIGFILE_NAME));
			}
		});
	}
	
	public Settings(File settingsfile) {
		this();
		this.getSettingsFromFile(settingsfile);
	}
	
	public void getSettingsFromFile(File settingsfile) {
		try {
			Scanner scan = new Scanner(new File(CONFIGFILE_NAME));
			while (scan.hasNextLine()) {
				this.parseSettingLine(scan.nextLine());
			}
		} catch (FileNotFoundException e) {
			System.out.println("Config file not found - using defaults.");
		}
	}
	
	public void printSettingsToFile(File settingsfile) {
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(new File(CONFIGFILE_NAME)));
			for (String s : this.settings.keySet()) {
				writer.write(s+"="+this.getValue(s));
				writer.newLine();
			}
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void parseSettingLine(String line) {
		String[] lines = line.split("=");
		if (lines.length == 2) {
			this.setValue(lines[0], lines[1]);
		}
	}
	
	public void setDefaults() {
		this.setValue(ITUNES_LIBRARY, "");
		this.setValue(MOBILE_LIBRARY_DIR, "");
		this.setValue(LIBRARY_FILENAME, "MobileLibrary.xml");
		this.setValue(SYNC_ENTIRE_LIBRARY, "yes");
	}
	
	public String getValue(String name) {
		return this.settings.get(name);
	}
	
	public void setValue(String name, String value) {
		//System.out.println(name+" - "+value);
		this.settings.put(name, value);
	}
	
}
