package com.bitnix.dirtcryptostore.manager;

import com.bitnix.dirtcryptostore.DirtCryptoStorePlugin;
import com.bitnix.dirtcryptostore.model.PendingInvoice;
import com.bitnix.dirtcryptostore.util.ColorUtil;
import com.bitnix.dirtcryptostore.util.QrMapUtil;
import com.bitnix.dirtcryptostore.util.QrPlaceholderUtil;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

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

public class QrMapManager {

    private final DirtCryptoStorePlugin plugin;
    private final Map<UUID, ItemStack> activeQrMaps = new HashMap<>();

    public QrMapManager(DirtCryptoStorePlugin plugin) {
        this.plugin = plugin;
    }

    public ItemStack createQrMap(Player player, PendingInvoice invoice) {
        String bitcoinUri = QrPlaceholderUtil.buildBitcoinUri(invoice);

        return QrMapUtil.createQrMapItem(
                plugin,
                player,
                bitcoinUri,
                ColorUtil.color("&aScan QR To Pay"),
                java.util.List.of(
                        ColorUtil.color("&7Invoice: &f" + invoice.getInvoiceId()),
                        ColorUtil.color("&7Amount: &f" + com.bitnix.dirtcryptostore.util.TimeUtil.formatBtcAmount(invoice.getAmountSats())),
                        ColorUtil.color("&7Address: &f" + invoice.getWalletAddress()),
                        ColorUtil.color("&7Use /cryptostore to reopen controls.")
                ),
                plugin.getConfig().getString("settings.qr.fallback-material-if-map-fails", "PAPER")
        );
    }

    public void giveToOffhand(Player player, PendingInvoice invoice) {
        ItemStack qrMap = createQrMap(player, invoice);
        activeQrMaps.put(player.getUniqueId(), qrMap);
        player.getInventory().setItemInOffHand(qrMap);
        player.updateInventory();
    }

    public void clear(Player player) {
        activeQrMaps.remove(player.getUniqueId());
    }

    public ItemStack getActiveMap(UUID uuid) {
        return activeQrMaps.get(uuid);
    }

    public boolean hasActiveMap(UUID uuid) {
        return activeQrMaps.containsKey(uuid);
    }

    public void clearAll() {
        activeQrMaps.clear();
    }
}
