/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.configplayer;

import de.steamwar.bausystem.configplayer.serializer.ConfigurationSerializableSerializer;
import de.steamwar.linkage.Linked;
import de.steamwar.sql.UserConfig;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import yapion.hierarchy.output.StringOutput;
import yapion.hierarchy.types.YAPIONObject;
import yapion.parser.YAPIONParser;
import yapion.serializing.SerializeManager;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;

@Linked
public class Config implements Listener {

    static {
        SerializeManager.add(new ConfigurationSerializableSerializer());
    }

    @Getter
    private static Config instance;

    {
        instance = this;
    }

    private final Map<UUID, YAPIONObject> playerConfigurations = new HashMap<>();

    private static final Map<Integer, ConfigConverter> CONFIG_CONVERTER_MAP = new HashMap<>();

    public static void addConfigConverter(ConfigConverter configConverter) {
        CONFIG_CONVERTER_MAP.putIfAbsent(configConverter.version(), configConverter);
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        get(event.getPlayer());
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        save(event.getPlayer());
        playerConfigurations.remove(event.getPlayer().getUniqueId());
    }

    /**
     * Get a PlayerConfig, optionally loads it from the DataBase and migrates it if necessary.
     *
     * @param player the player from whom to get the config.
     * @return the config object
     */
    public YAPIONObject get(Player player) {
        UUID uuid = player.getUniqueId();
        if (!playerConfigurations.containsKey(uuid)) {
            String s = UserConfig.getConfig(uuid, "bausystem");
            YAPIONObject yapionObject;
            if (s == null) {
                yapionObject = ConfigCreator.createDefaultConfig();
            } else {
                yapionObject = YAPIONParser.parse(s);
            }
            yapionObject = update(yapionObject);
            playerConfigurations.put(uuid, yapionObject);
            return yapionObject;
        }
        return playerConfigurations.get(uuid);
    }

    public void saveAll() {
        playerConfigurations.forEach((uuid, yapionObject) -> {
            String string = yapionObject.toYAPION(new StringOutput()).getResult().replaceAll("\\+", "\\");
            UserConfig.updatePlayerConfig(uuid, "bausystem", string);
        });
        playerConfigurations.clear();
    }

    /**
     * Save a PlayerConfig, this does not remove the key value mapping from the map.
     *
     * @param player the player to save the config.
     */
    public void save(Player player) {
        UUID uuid = player.getUniqueId();
        if (playerConfigurations.containsKey(uuid)) {
            YAPIONObject yapionObject = playerConfigurations.get(uuid);
            String string = yapionObject.toYAPION(new StringOutput()).getResult().replaceAll("\\\\+", "\\\\");
            UserConfig.updatePlayerConfig(uuid, "bausystem", string);
        }
    }

    private YAPIONObject update(YAPIONObject yapionObject) {
        int version = yapionObject.getPlainValue("@version");
        while (version < ConfigCreator.currentVersion) {
            ConfigConverter configConverter = CONFIG_CONVERTER_MAP.getOrDefault(version, null);
            if (configConverter == null) {
                Bukkit.getLogger().log(Level.SEVERE, "No updater found for version " + version);
                return ConfigCreator.createDefaultConfig();
            }
            try {
                configConverter.update(yapionObject);
            } catch (Exception e) {
                Bukkit.getLogger().log(Level.SEVERE, e.getMessage(), e);
                return ConfigCreator.createDefaultConfig();
            }
            int newVersion = yapionObject.getPlainValue("@version");
            if (version == newVersion) {
                Bukkit.getLogger().log(Level.SEVERE, "Version Tag was the same after conversion");
                return ConfigCreator.createDefaultConfig();
            }
            if (newVersion < version) {
                Bukkit.getLogger().log(Level.SEVERE, "Version Tag was earlier after conversion");
                return ConfigCreator.createDefaultConfig();
            }
            version = newVersion;
        }
        return yapionObject;
    }
}
