package ru.kirillius.cooler.controller;

import ru.kirillius.cooler.controller.CLI.ConsoleApp;
import ru.kirillius.cooler.controller.UI.MainForm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Properties;

public class Application {
    public final static boolean DEBUG;
    public final static String title = "Cooler configurator";
    public final static Properties properties = new Properties();
    public final static boolean WINDOWS_HOST = System.getProperty("os.name").toLowerCase().contains("windows");
    private final static File configFile;

    static {
        var props = System.getProperties();
        DEBUG = props.containsKey("debug") && props.getProperty("debug").equals("true");
        if (DEBUG) System.out.println("Debug mode is enabled");

        File location = new File(".");
        if (WINDOWS_HOST) try {
            location = new File(Application.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
        } catch (URISyntaxException ignored) {
        }
        if (!location.exists()) {
            location = new File(".");
        }

        configFile = new File(location, "config.ini");
    }

    public static void saveConfig() throws IOException {
        try (FileOutputStream stream = new FileOutputStream(configFile)) {
            properties.store(stream, "");
        }
    }

    public static void main(String[] args) throws IOException {
        if (configFile.exists()) {
            try (FileInputStream stream = new FileInputStream(configFile)) {
                properties.load(stream);
            }
        }

        boolean gui = true;
        for (String arg : args) {
            if (arg.equals("--cli")) {
                gui = false;
                break;
            }
        }

        if (gui) {
            MainForm mainForm = new MainForm();
            mainForm.setVisible(true);
        } else {
            new ConsoleApp();
        }

    }
}
