package shop.morpheusnox.backpackInfinita;

import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public final class BackpackInfinita extends JavaPlugin {

    private Database database;
    private Map<UUID, Backpack> playerBackpacks;

    @Override
    public void onEnable() {
        // Lógica de inicialização do plugin
        this.database = new Database(this.getDataFolder());
        this.playerBackpacks = new HashMap<>();

        this.getCommand("backpack").setExecutor(new BackpackCommand(this));
        this.getServer().getPluginManager().registerEvents(new BackpackListener(this), this);
    }

    @Override
    public void onDisable() {
        // Lógica de desligamento do plugin
        // Salva todas as mochilas em cache no banco de dados
        for (Map.Entry<UUID, Backpack> entry : playerBackpacks.entrySet()) {
            savePlayerBackpack(entry.getKey(), entry.getValue());
        }
    }

    public Database getDatabase() {
        return database;
    }

    public Backpack getPlayerBackpack(Player player) {
        UUID playerUUID = player.getUniqueId();
        if (playerBackpacks.containsKey(playerUUID)) {
            return playerBackpacks.get(playerUUID);
        }

        Backpack backpack = new Backpack(player);
        try (PreparedStatement statement = getDatabase().getConnection().prepareStatement("SELECT items FROM backpacks WHERE uuid = ?")) {
            statement.setString(1, playerUUID.toString());
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                backpack.fromBase64(resultSet.getString("items"));
            }
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
        playerBackpacks.put(playerUUID, backpack);
        return backpack;
    }

    public void savePlayerBackpack(UUID playerUUID, Backpack backpack) {
        try (PreparedStatement statement = getDatabase().getConnection().prepareStatement("REPLACE INTO backpacks (uuid, items) VALUES (?, ?)")) {
            statement.setString(1, playerUUID.toString());
            statement.setString(2, backpack.toBase64());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void removePlayerBackpack(UUID playerUUID) {
        playerBackpacks.remove(playerUUID);
    }
}
