package com.yourname.premiumah.economy;

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 org.bukkit.plugin.java.JavaPlugin;

import java.text.DecimalFormat;

public final class VaultEconomyService implements EconomyService {
    private static final DecimalFormat FALLBACK_FORMAT = new DecimalFormat("#,##0.##");

    private final JavaPlugin plugin;
    private Economy economy;

    public VaultEconomyService(JavaPlugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public void reload() {
        this.economy = null;
        if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
            plugin.getLogger().warning("Vault is not installed. Dirt Auctions marketplace functions are disabled.");
            return;
        }
        RegisteredServiceProvider<Economy> registration = Bukkit.getServicesManager().getRegistration(Economy.class);
        if (registration == null || registration.getProvider() == null) {
            plugin.getLogger().warning("Vault is installed, but no economy provider is registered. Dirt Auctions marketplace functions are disabled.");
            return;
        }
        this.economy = registration.getProvider();
        plugin.getLogger().info("Hooked economy provider: " + economy.getName());
    }

    @Override
    public boolean isAvailable() {
        return economy != null;
    }

    @Override
    public String providerName() {
        return economy == null ? "Vault" : economy.getName();
    }

    @Override
    public boolean has(OfflinePlayer player, double amount) {
        if (amount <= 0.0D) {
            return true;
        }
        return economy != null && economy.has(player, amount);
    }

    @Override
    public boolean withdraw(OfflinePlayer player, double amount) {
        if (amount <= 0.0D) {
            return true;
        }
        if (economy == null) {
            return false;
        }
        EconomyResponse response = economy.withdrawPlayer(player, amount);
        return response.transactionSuccess();
    }

    @Override
    public boolean deposit(OfflinePlayer player, double amount) {
        if (amount <= 0.0D) {
            return true;
        }
        if (economy == null) {
            return false;
        }
        EconomyResponse response = economy.depositPlayer(player, amount);
        return response.transactionSuccess();
    }

    @Override
    public String format(double amount) {
        if (economy == null) {
            return "$" + FALLBACK_FORMAT.format(amount);
        }
        return economy.format(amount);
    }
}
