package controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.List;

import model.Settings;
import ui.Main;

/**
 * Save and Load functions for the settings.ini
 * @author Martin Herbers
 *
 */
public class SettingsController {

	private static Settings settings = Settings.getSettings();
	
	/**
	 * Create or override a settings.ini file with all necessary information
	 */
	public static void saveSettings() {
		try {
			File file = new File(Main.olipPath + "settings.ini");
			new File(Main.olipPath).mkdirs();
			PrintWriter writer = new PrintWriter(file);
			writer.print("[Settings]\r\n");
			writer.print("Fill=" + settings.getFill() + "\r\n");
			writer.print("SizeScreen=" + settings.getSizeScreen() + "\r\n");
			writer.print("SizeFinger=" + settings.getSizeFinger() + "\r\n");
			writer.print("OpenSCADPath=" + settings.getOpenSCADPath());
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Parse the settings.ini
	 */
	public static void loadSettings() {
		try {
			File file = new File(Main.olipPath + "settings.ini");
			if (file.exists()) {
				List<String> lines = Files.readAllLines(file.toPath());
				settings.setFill(Boolean.parseBoolean(lines.get(1).substring(lines.get(1).indexOf('=')+1)));
				settings.setSizeScreen(Float.parseFloat(lines.get(2).substring(lines.get(2).indexOf('=')+1)));
				settings.setSizeFinger(Float.parseFloat(lines.get(3).substring(lines.get(3).indexOf('=')+1)));
				String path = lines.get(4).substring(lines.get(4).indexOf('=')+1);
				if (path.equals("null"))
					settings.setOpenSCADPath(null);
				else
					settings.setOpenSCADPath(new File(path).toPath());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
