package net.viper.status.modules.chat;

import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * Verwaltet Mutes von Spielern.
 * Speichert: UUID → Ablaufzeitpunkt (Unix-Sekunden, 0 = permanent)
 *
 * Admins/OPs mit dem Bypass-Permission k\u00f6nnen nicht gemutet werden.
 */
public class MuteManager {

    private final File file;
    private final Logger logger;

    // UUID → Ablaufzeitpunkt (0 = permanent)
    private final ConcurrentHashMap<UUID, Long> mutes = new ConcurrentHashMap<>();

    public MuteManager(File dataFolder, Logger logger) {
        this.file   = new File(dataFolder, "chat_mutes.dat");
        this.logger = logger;
    }

    // ===== Mute-Logik =====

    /**
     * Mutet einen Spieler f\u00fcr durationMinutes Minuten.
     * durationMinutes = 0 → permanent
     */
    public void mute(UUID uuid, int durationMinutes) {
        long expiry = (durationMinutes <= 0)
                ? 0L
                : (System.currentTimeMillis() / 1000L) + ((long) durationMinutes * 60);
        mutes.put(uuid, expiry);
        save();
    }

    /** Hebt den Mute auf. */
    public void unmute(UUID uuid) {
        mutes.remove(uuid);
        save();
    }

    /** Pr\u00fcft ob ein Spieler aktuell gemutet ist. */
    public boolean isMuted(UUID uuid) {
        Long expiry = mutes.get(uuid);
        if (expiry == null) return false;
        if (expiry == 0L) return true; // permanent
        if (System.currentTimeMillis() / 1000L >= expiry) {
            // Abgelaufen → entfernen
            mutes.remove(uuid);
            save();
            return false;
        }
        return true;
    }

    /**
     * Gibt die verbleibende Zeit als lesbaren String zur\u00fcck.
     * Gibt "permanent" zur\u00fcck bei dauerhaftem Mute.
     */
    public String getRemainingTime(UUID uuid) {
        Long expiry = mutes.get(uuid);
        if (expiry == null) return "0";
        if (expiry == 0L) return "permanent";

        long remaining = expiry - (System.currentTimeMillis() / 1000L);
        if (remaining <= 0) return "0";

        long hours   = remaining / 3600;
        long minutes = (remaining % 3600) / 60;
        long seconds = remaining % 60;

        if (hours > 0)   return hours + "h " + minutes + "m";
        if (minutes > 0) return minutes + "m " + seconds + "s";
        return seconds + "s";
    }

    // ===== Persistenz =====

    public void save() {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
            long now = System.currentTimeMillis() / 1000L;
            for (Map.Entry<UUID, Long> e : mutes.entrySet()) {
                // Nur aktive Mutes speichern
                if (e.getValue() == 0L || e.getValue() > now) {
                    bw.write(e.getKey() + "|" + e.getValue());
                    bw.newLine();
                }
            }
        } catch (IOException e) {
            logger.warning("[ChatModule] Fehler beim Speichern der Mutes: " + e.getMessage());
        }
    }

    public void load() {
        mutes.clear();
        if (!file.exists()) return;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
            String line;
            long now = System.currentTimeMillis() / 1000L;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue;
                String[] parts = line.split("\\|");
                if (parts.length < 2) continue;
                try {
                    UUID uuid   = UUID.fromString(parts[0]);
                    long expiry = Long.parseLong(parts[1]);
                    // Nur laden wenn noch aktiv
                    if (expiry == 0L || expiry > now) {
                        mutes.put(uuid, expiry);
                    }
                } catch (Exception ignored) {}
            }
        } catch (IOException e) {
            logger.warning("[ChatModule] Fehler beim Laden der Mutes: " + e.getMessage());
        }
    }
}