package com.io.yutian.boxsimulate.gui;

import cn.hamster3.cdapi.CDTimeAPI;
import com.io.yutian.boxsimulate.BoxSimulate;
import com.io.yutian.boxsimulate.data.BoxData;
import com.praya.myitems.MyItems;
import com.yaohun.itemlibrary.api.ItemKuAPI;
import me.Demon.DemonPlugin.DemonAPI;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BoxSimulateGui implements InventoryHolder, GuiHolder {

    private Inventory inventory;
    private Player player;

    private Map<Integer, String> cacheItems = new HashMap<>();

    public BoxSimulateGui(Player player) {
        this.inventory = Bukkit.createInventory(this, 54, "开箱模拟器");
        this.player = player;
        init();
    }

    private void init() {
        Map<String, BoxData> boxDatas = BoxSimulate.getBoxDatas();
        List<BoxData> boxDataList = boxDatas.values().stream().collect(Collectors.toList());
        int i = 0;
        for (Map.Entry<String, BoxData> entry : boxDatas.entrySet()) {
            BoxData boxData = boxDataList.get(i);
            if (!DemonAPI.hasPoints(player, boxData.getNeed())) {
                continue;
            }
            ItemStack itemStack = getBoxItem(boxData.getItem());
            inventory.setItem(i, itemStack);
            cacheItems.put(i, entry.getKey());
            i++;
        }
    }

    private ItemStack getBoxItem(String id) {
        return ItemKuAPI.getItems(id);
    }

    private ItemStack generateItem(String item) {
        MyItems myItems = (MyItems) Bukkit.getPluginManager().getPlugin("MyItems");
        return myItems.getGameManager().getItemGeneratorManager().getItemGenerator(item).generateItem();
    }

    @Override
    public void onClick(InventoryClickEvent event) {
        int slot = event.getRawSlot();
        event.setCancelled(true);
        if (slot >= 54) {
            return;
        }
        if (!cacheItems.containsKey(slot)) {
            return;
        }
        String id = cacheItems.get(slot);
        if (CDTimeAPI.isCD(player.getUniqueId(), "box_simulate_box_"+id)) {
            player.sendMessage("§8§l[§c§l!§8§l] §7该箱子冷却中...");
            return;
        }
        BoxData boxData = BoxSimulate.getBoxDatas().get(id);
        inventory.setItem(slot, generateItem(boxData.getItem()));
        CDTimeAPI.setPlayerCD(player.getUniqueId(), "box_simulate_box_"+id, 1000 * 60 * 60);
    }

    @Override
    public void onClose(InventoryCloseEvent event) {
    }

    @Override
    public void open() {
        player.openInventory(inventory);
    }

    @Override
    public Inventory getInventory() {
        return inventory;
    }

}
