package net.viper.status.stats;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * Fix #9: save() und load() sind jetzt synchronized um Race Conditions
 * zwischen Auto-Save-Task und Shutdown-Aufruf zu verhindern.
 */
public class StatsStorage {
    private final File file;
    private final Object fileLock = new Object();

    public StatsStorage(File pluginFolder) {
        if (!pluginFolder.exists()) pluginFolder.mkdirs();
        this.file = new File(pluginFolder, "stats.dat");
    }

    public void save(StatsManager manager) {
        synchronized (fileLock) {
            // Atomares Schreiben: erst in .tmp, dann umbenennen.
            // Verhindert korrupte stats.dat bei Server-Absturz während des Schreibvorgangs.
            File tmp = new File(file.getParentFile(), "stats.dat.tmp");
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(tmp))) {
                for (PlayerStats ps : manager.all()) {
                    bw.write(ps.toLine());
                    bw.newLine();
                }
                bw.flush();
            } catch (IOException e) {
                e.printStackTrace();
                return; // Nicht umbenennen bei Fehler
            }
            try {
                Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void load(StatsManager manager) {
        if (!file.exists()) return;
        synchronized (fileLock) {
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = br.readLine()) != null) {
                    PlayerStats ps = PlayerStats.fromLine(line);
                    if (ps != null) manager.put(ps);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
