package com.screenshot.config;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

public class AppConfig {
    private static final String CONFIG_FILE = "config.properties";
    private final Properties properties;

    public AppConfig() {
        properties = new Properties();
        loadConfig();
    }

    private void loadConfig() {
        Path configPath = Path.of(CONFIG_FILE);
        if (Files.exists(configPath)) {
            try (FileInputStream fis = new FileInputStream(CONFIG_FILE)) {
                properties.load(fis);
            } catch (IOException e) {
                System.err.println("Ошибка загрузки конфигурации: " + e.getMessage());
                setDefaults();
            }
        } else {
            setDefaults();
            saveConfig();
        }
    }

    private void setDefaults() {
        properties.setProperty("save.path", System.getProperty("user.home") + "/Screenshots");
        properties.setProperty("schedule.cron", "0 * * * * *");
        properties.setProperty("target.window", "");
        properties.setProperty("schedule.interval.minutes", "1");
        properties.setProperty("use.cron", "false");
    }

    public void saveConfig() {
        try (FileOutputStream fos = new FileOutputStream(CONFIG_FILE)) {
            properties.store(fos, "Screenshot Application Configuration");
        } catch (IOException e) {
            System.err.println("Ошибка сохранения конфигурации: " + e.getMessage());
        }
    }

    public String getSavePath() {
        return properties.getProperty("save.path");
    }

    public void setSavePath(String path) {
        properties.setProperty("save.path", path);
    }

    public String getCronExpression() {
        return properties.getProperty("schedule.cron");
    }

    public void setCronExpression(String cron) {
        properties.setProperty("schedule.cron", cron);
    }

    public String getTargetWindow() {
        return properties.getProperty("target.window", "");
    }

    public void setTargetWindow(String windowTitle) {
        properties.setProperty("target.window", windowTitle);
    }

    public int getIntervalMinutes() {
        return Integer.parseInt(properties.getProperty("schedule.interval.minutes", "1"));
    }

    public void setIntervalMinutes(int minutes) {
        properties.setProperty("schedule.interval.minutes", String.valueOf(minutes));
    }

    public boolean useCron() {
        return Boolean.parseBoolean(properties.getProperty("use.cron", "false"));
    }

    public void setUseCron(boolean useCron) {
        properties.setProperty("use.cron", String.valueOf(useCron));
    }
}
