package com.yuyu.srdisassemble.disassemeble;

import com.germ.germplugin.api.dynamic.gui.*;
import com.sakurarealm.sritem.api.ItemStackHelper;
import com.sakurarealm.sritem.api.SrItemAPI;
import com.sakurarealm.sritem.api.builder.SrItemHandler;
import com.yuyu.srdisassemble.SrDisassemble;
import com.yuyu.srdisassemble.data.JdbcSqlClass;
import com.yuyu.srdisassemble.data.SqlData;
import com.yuyu.srdisassemble.pojo.CanDisItem;
import com.yuyu.srdisassemble.pojo.DisProduct;
import com.yuyu.srdisassemble.pojo.DisassembleData;
import com.yuyu.srdisassemble.utils.MinUtil;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author 峰。
 * @version 1.0
 * @project SrDisassemble
 * @date 2024/6/11 17:01:05
 * @description 用于给分解gui提供服务的类
 */
public class SassembleGuiService extends GermGuiScreen {
    private DisassembleData data;
    private String name;
    private Random random ;
    private boolean disassemble = true;
    private Player playerHost;
    private GermGuiScreen temporarilyBoxScreen;

    public SassembleGuiService(ConfigurationSection configurationSection, String guiName,Player playerHost) {
        super(guiName, configurationSection);
        this.playerHost = playerHost;
        this.data = JdbcSqlClass.getDataByGuiAndPlay(playerHost.getName(), guiName);
        this.registerDisassemble();
        this.random = new Random();
        this.name = playerHost.getName();
        this.getTemporarilyBox();
        this.boolGui();
        this.setClosedHandler(((player, germGuiScreen) -> {
            //窗口关闭事件
            this.returnItemStacks(player);
            this.saveTemporarilyBox();
            this.close();
        }));
    }

    /**
     * 获取暂存箱对象
     */
    public void getTemporarilyBox(){
        this.temporarilyBoxScreen = TemporarilyBox.getGermGuiScreen(playerHost.getName(), "TemporarilyBox");
        if (temporarilyBoxScreen == null) {
            temporarilyBoxScreen = GermGuiScreen.getGermGuiScreen("TemporarilyBox", DisassembleManager.getTemporarilyBox());
            TemporarilyBox.addGuiScreen(playerHost.getName(),"TemporarilyBox",temporarilyBoxScreen);
        }
    }

    /**
     * 用于关闭暂存箱
     */
    public void closeTemporaryBox(){
        this.temporarilyBoxScreen.close();
    }

    /**
     * gui关闭时保存暂存箱
     */
    public void saveTemporarilyBox(){
        TemporarilyBox.addGuiScreen(playerHost.getName(), "TemporarilyBox",this.temporarilyBoxScreen);
    }

    public void boolGui(){
        if (data.getId() != 0 && data.getTargetIndex() != null) {
            GermGuiSlot disassembleSlot = (GermGuiSlot) this.getGuiPart("disassembleSlot");
            disassembleSlot.setInteract(false);
            disassembleSlot.setItemStack(SrItemAPI.getItem(data.getTargetIndex(),
                    new HashMap<>(),null,true,true));

            GermGuiGif fire = (GermGuiGif) this.getGuiPart("fire");
            GermGuiTexture men1 = (GermGuiTexture) this.getGuiPart("men1");
            GermGuiTexture doorPause = (GermGuiTexture) this.getGuiPart("doorPause");
            GermGuiGif door = (GermGuiGif) this.getGuiPart("door");

            men1.setEnable(false);
            fire.setEnable(true);
            doorPause.setEnable(true);

            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();


//            executor.schedule(() ->{
//                //打开暂存箱
//                temporarilyBoxScreen.openChildGui(playerHost);
//
//            },100,TimeUnit.MILLISECONDS);
            executor.scheduleAtFixedRate(() -> {
                int calculateMinutesDifference = MinUtil.calculateMinutesDifference(data.getDisassembleTime());
                if (calculateMinutesDifference <= 0) {
                    //执行语句说明分解完成
                    this.disassembleComplete();
                    if ((boolean)disassembleSlot.getInteract() == true && disassemble){
                        JdbcSqlClass.deleteData(data.getId());

                        //赋予产物后把火关掉，门打开
                        //TODO(此处后面可以让美术大佬做一个开炉门的gif
                        fire.setEnable(false);
                        door.setEnable(false);
                        men1.setEnable(true);
                        doorPause.setEnable(false);
                        this.openTemporarilyBox();
                        executor.shutdownNow();
                    }

                }

            },0, 1 , TimeUnit.MINUTES);
            //0延迟，minTime分钟后执行
        }else {
            this.openTemporarilyBox();
        }
    }


    public void openTemporarilyBox(){
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(() -> {
            this.temporarilyBoxScreen.openChildGui(this.playerHost);
        },100,TimeUnit.MILLISECONDS);

    }

    /**
     * 注册分解事件
     */
    public void registerDisassemble() {
        //获取画布
        GermGuiCanvas canvas = (GermGuiCanvas)this.getGuiPart("canvas");
        //通过画布获取按键
        GermGuiButton confirmButton = (GermGuiButton) canvas.getGuiPart("confirmButton");
        GermGuiButton cancleButton = (GermGuiButton) canvas.getGuiPart("cancleButton");
        GermGuiButton germGuiButton =(GermGuiButton) this.getGuiPart("youhu");
        GermGuiSlot disassembleSlot = (GermGuiSlot) this.getGuiPart("disassembleSlot");

        confirmButton.registerCallbackHandler((player, btn) -> {
                this.disassemble(player);
                canvas.setEnable(false);
        },GermGuiButton.EventType.LEFT_CLICK);

        //取消事件
        cancleButton.registerCallbackHandler((player, btn) -> {
            //取消事件,关闭画布gui
            canvas.setEnable(false);
        },GermGuiButton.EventType.LEFT_CLICK);

        //油壶按钮绑定的事件触发画布显示
        germGuiButton.registerCallbackHandler((player, btn) -> {
            if ((boolean)disassembleSlot.getInteract()) {
                canvas.setEnable(true);
            }
        },GermGuiButton.EventType.LEFT_CLICK);
    }

    public void disassemble(Player player){

        GermGuiSlot disassembleSlot = (GermGuiSlot) this.getGuiPart("disassembleSlot");
        if ((boolean)disassembleSlot.getInteract() == false){
            //正在分解某种物品
            return;
        }
        ItemStack itemStack = disassembleSlot.getItemStack();
        if (itemStack.getType() == Material.AIR || itemStack == null) {
            player.sendMessage(Color.RED+"在熔炉物品框中放上可分解的物品!");
            return;
        }
        SrItemHandler srItemHandler = ItemStackHelper.getSrItemHandler(itemStack);
        String title = srItemHandler.getTitle();
        //这个是item的名字
        String itemName = title.substring(title.indexOf('l') + 1);
        HashMap<String, CanDisItem> disProductHashMap = SrDisassemble.getConfigManager().getDisProductHashMap();
        CanDisItem canDisItem = disProductHashMap.get(itemName);
        if (!disProductHashMap.containsKey(itemName)){
            player.sendMessage(Color.RED+"放入的物品不可分解!");
            return;
        }
        disassembleSlot.setInteract(false);//关闭交互
        //上方if语句通过表示该物品可以分解
        //假如启动按钮是油壶，
        GermGuiGif door = (GermGuiGif) this.getGuiPart("door");
        door.setCycle(1);
        if ((boolean)door.getEnable() == true){
            return;
        }
        GermGuiTexture men1 = (GermGuiTexture) this.getGuiPart("men1");
        men1.setEnable(false);
        GermGuiGif fire = (GermGuiGif) this.getGuiPart("fire");
        fire.setEnable(true);
        door.setEnable(true);
        this.data = new DisassembleData(player.getName(),
                MinUtil.calculateTimeAfterMinutes(canDisItem.getDisTime()),
                canDisItem.getTarget(), canDisItem.getTargetIndex(), this.getGuiName(),itemStack.getAmount());
        //此处向数据库中插入数据,并且注册定时器计算时间
        int i = JdbcSqlClass.insertData(data);
        data.setId(i);

        //下面写注册逻辑,完成的时间已经记录在data里面了!!!

        this.closeTemporaryBox();

        int minTime = MinUtil.calculateMinutesDifference(data.getDisassembleTime());

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

//        executor.schedule(() ->{
//            //打开暂存箱
//            temporarilyBoxScreen.openChildGui(playerHost);
//
//        },1,TimeUnit.SECONDS);

        executor.scheduleAtFixedRate(() -> {
            int calculateMinutesDifference = MinUtil.calculateMinutesDifference(data.getDisassembleTime());
            if (calculateMinutesDifference <= 0) {
                //执行语句说明分解完成
                this.disassembleComplete();
                if ((boolean)disassembleSlot.getInteract() == true && disassemble){
                    JdbcSqlClass.deleteData(data.getId());

                    //赋予产物后把火关掉，门打开
                    //TODO(此处后面可以让美术大佬做一个开炉门的gif
                    fire.setEnable(false);
                    door.setEnable(false);
                    men1.setEnable(true);
                    this.openTemporarilyBox();
                    executor.shutdownNow();
                }
            }

        },1, 1, TimeUnit.MINUTES);
            //1分钟延迟，minTime分钟后执行




//        //此处写分解逻辑
//        int itemAmount = itemStack.getAmount();
//        //分解物品返回原胚，理论上是只能单次分解一个然后得到一个。
//        HashMap<String, DisProduct> stringDisProductHashMap = disProductHashMap.get(itemName);
//        float v = random.nextFloat();
//        ItemStack product = null;
//        for (DisProduct disProduct : stringDisProductHashMap.values()) {
//            if (disProduct.getProMax() > v && disProduct.getProMin() <= v){
//                product = SrItemAPI.getItem(disProduct.getIndexName(),new HashMap<>(),null,true,true);
//                break;
//            }
//        }
//        disassembleSlot.setInteract(true);
//        //赋予产物
//        disassembleSlot.setItemStack(product);
    }

    /**
     * 此方法用于获取产物
     */
    public void disassembleComplete(){
        GermGuiSlot disassembleSlot = (GermGuiSlot) this.getGuiPart("disassembleSlot");
        ItemStack itemStack = disassembleSlot.getItemStack();
        //此处写分解逻辑
        int itemAmount = itemStack.getAmount();
        SrItemHandler srItemHandler = ItemStackHelper.getSrItemHandler(itemStack);
        String title = srItemHandler.getTitle();
        //这个是item的名字
        String itemName = title.substring(title.indexOf('l') + 1);

        HashMap<String, CanDisItem> disProductHashMap = SrDisassemble.getConfigManager().getDisProductHashMap();
        //分解物品返回原胚，理论上是只能单次分解一个然后得到一个。
       CanDisItem canDisItem = disProductHashMap.get(itemName);
        HashMap<String, DisProduct> disProducts = canDisItem.getDisProductHashMap();
        float v = random.nextFloat();
        ItemStack product = null;
        for (DisProduct disProduct : disProducts.values()) {
            if (disProduct.getProMax() > v && disProduct.getProMin() <= v){
                product = SrItemAPI.getItem(disProduct.getIndexName(),new HashMap<>(),null,true,true);
                break;
            }
        }
        disassembleSlot.setInteract(true);
        //赋予产物
        disassembleSlot.setItemStack(product);
    }

    //遍历gui的所有物品槽，并且返回到玩家背包中
    synchronized private void returnItemStacks(Player player) {
        this.disassemble = false;
        this.temporarilyBoxScreen.close();
        List<GermGuiSlot> allGuiParts = this.getAllGuiParts(GermGuiSlot.class);
        for (GermGuiSlot guiPart : allGuiParts) {
            if ((guiPart.getItemStack().getType() != Material.AIR || guiPart.getItemStack() == null) && (boolean)guiPart.getInteract()) {
                player.getInventory().addItem(guiPart.getItemStack());
            }
        }
    }

}
