package de.miaurizius.jgame2d.data;

import de.miaurizius.jgame2d.core.GamePanel;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Config {

    private final GamePanel panel;
    private final HashMap<String, String> settings = new HashMap<>();

    public Config(GamePanel panel) throws IOException {
        this.panel = panel;
        for (Setting option : Setting.values()) settings.put(option.name, null);
        new File("gamedata").mkdirs();
        new File("gamedata/save").mkdirs();
        new File("gamedata/config").createNewFile();
    }

    // GENERAL
    public final void save() {
        try {
            insertToHash();
            BufferedWriter writer = new BufferedWriter(new FileWriter("gamedata/config"));
            settings.forEach((invoke, value) -> {
                try {
                    writer.write(invoke + ": " + value);
                    writer.newLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            writer.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public final void load() {
        try (BufferedReader reader = new BufferedReader(new FileReader("gamedata/config"))) {
            List<String> lines = reader.lines().toList();
            if (lines.isEmpty()) return;
            Map<String, String> configMap = new HashMap<>();
            for (String line : lines) {
                String[] parts = line.split(":\\s*", 2);
                if (parts.length == 2) {
                    configMap.put(parts[0].trim(), parts[1].trim());
                }
            }

            for (Setting setting : Setting.values()) {
                String value = configMap.get(setting.name);
                if (value != null) {
                    switch (setting) {
                        case FULLSCREEN -> panel.fullscreen = Boolean.parseBoolean(value);
                        case MUSICVOLUME -> panel.music.volumeScale = Integer.parseInt(value);
                        case SFXVOLUME -> panel.sfx.volumeScale = Integer.parseInt(value);
                    }
                }
            }
            insertToHash();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // HELP FUNCTIONS
    private void insertToHash() {
        settings.put(Setting.FULLSCREEN.name, String.valueOf(panel.fullscreen));
        settings.put(Setting.MUSICVOLUME.name, String.valueOf(panel.music.volumeScale));
        settings.put(Setting.SFXVOLUME.name, String.valueOf(panel.sfx.volumeScale));
    }

    private enum Setting {
        FULLSCREEN("fullscreen"),
        MUSICVOLUME("music-vol"),
        SFXVOLUME("sfx-vol");

        private final String name;

        Setting(String name) {
            this.name = name;
        }
    }

}
