package com.io.yutian.boxsimulate;

import com.io.yutian.boxsimulate.data.BoxData;
import com.io.yutian.boxsimulate.gui.BoxSimulateGui;
import com.io.yutian.boxsimulate.gui.GuiHolder;
import com.io.yutian.boxsimulate.listener.GuiListener;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.plugin.java.JavaPlugin;

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

public final class BoxSimulate extends JavaPlugin {

    private static BoxSimulate instance;

    private static Map<String, BoxData> boxDatas = new HashMap<>();

    @Override
    public void onEnable() {
        instance = this;
        reload();
        Bukkit.getPluginManager().registerEvents(new GuiListener(), this);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (args.length == 1 && args[0].equalsIgnoreCase("reload")) {
            reloadConfig();
            reload();
            sender.sendMessage("模拟开箱配置文件已重载.");
            return true;
        }
        if (sender instanceof Player) {
            new BoxSimulateGui((Player) sender).open();
        }
        return true;
    }

    private void reload() {
        boxDatas.clear();
        saveDefaultConfig();
        reloadConfig();
        FileConfiguration config = getConfig();
        for (String key : config.getKeys(false)) {
            int need = config.getInt(key + ".need");
            String item = config.getString(key + ".item");
            boxDatas.put(key, new BoxData(need, item));
        }
    }

    public static Map<String, BoxData> getBoxDatas() {
        return boxDatas;
    }

    @Override
    public void onDisable() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (player.getOpenInventory() != null) {
                InventoryHolder inventoryHolder = player.getOpenInventory().getTopInventory().getHolder();
                if (inventoryHolder instanceof GuiHolder) {
                    player.closeInventory();
                }
            }
        }
    }

}
