package com.spaceshipproject;

import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.plugin.RegisteredServiceProvider;

import java.util.UUID;

/**
 * Wrapper autour de Vault. La seule source d'argent du plugin est l'economie expose par Vault
 * (EssentialsEconomy par defaut). Aucune monnaie n'est stockee dans la base du plugin.
 */
public class EconomyHook {

    private final SpaceShipProject plugin;
    private Economy economy;

    public EconomyHook(SpaceShipProject plugin) {
        this.plugin = plugin;
    }

    /** Initialise l'integration Vault. Retourne true si OK. */
    public boolean setup() {
        if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) {
            plugin.getLogger().warning("Vault est introuvable : les fonctionnalites economiques seront desactivees.");
            return false;
        }
        RegisteredServiceProvider<Economy> rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class);
        if (rsp == null) {
            plugin.getLogger().warning("Aucun fournisseur d'economie Vault detecte (EssentialsEconomy ?). Economie desactivee.");
            return false;
        }
        this.economy = rsp.getProvider();
        plugin.getLogger().info("Vault detecte, fournisseur : " + economy.getName());
        return true;
    }

    public boolean isReady() { return economy != null; }

    public double getBalance(UUID uuid) {
        if (!isReady()) return 0;
        OfflinePlayer p = Bukkit.getOfflinePlayer(uuid);
        return economy.getBalance(p);
    }

    public boolean has(UUID uuid, double amount) {
        if (!isReady()) return false;
        OfflinePlayer p = Bukkit.getOfflinePlayer(uuid);
        return economy.has(p, amount);
    }

    /** Retire `amount` au joueur. True si succes. */
    public boolean withdraw(UUID uuid, double amount) {
        if (!isReady()) return false;
        if (amount <= 0) return true;
        OfflinePlayer p = Bukkit.getOfflinePlayer(uuid);
        EconomyResponse r = economy.withdrawPlayer(p, amount);
        return r.transactionSuccess();
    }

    /** Depose `amount` au joueur. True si succes. */
    public boolean deposit(UUID uuid, double amount) {
        if (!isReady()) return false;
        if (amount <= 0) return true;
        OfflinePlayer p = Bukkit.getOfflinePlayer(uuid);
        EconomyResponse r = economy.depositPlayer(p, amount);
        return r.transactionSuccess();
    }

    public String format(double amount) {
        if (!isReady()) return String.valueOf(amount);
        return economy.format(amount);
    }
}
