package com.yuyu.srdisassemble.disassemeble;

import com.germ.germplugin.GermPlugin;
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.pojo.CanDisItem;
import com.yuyu.srdisassemble.pojo.DisProduct;
import com.yuyu.srdisassemble.pojo.DisassembleData;
import com.yuyu.srdisassemble.utils.MinUtil;
import org.bukkit.ChatColor;
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.ArrayList;
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 disassembleFlag = true;
    private Player playerHost;
    private GermGuiScreen temporarilyBoxScreen;
    private List<GermGuiSlot> guiSlots = new ArrayList<>();

    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.savePauseSlots();
        this.boolGui();
        this.openPauseBox();
        this.setClosedHandler(((player, germGuiScreen) -> {
            //窗口关闭事件
            this.returnItemStacks(player);
            this.saveTemporarilyBox();
            this.close();
        }));
    }

    private void savePauseSlots(){
        GermGuiCanvas canvas = (GermGuiCanvas) this.temporarilyBoxScreen.getGuiPart("canvas");
        GermGuiScroll scroll = (GermGuiScroll) canvas.getGuiPart("scroll");
        for (int i = 1; i <= 16 ; i++){
            String slotName = "slot_"+i;
            GermGuiSlot slot = (GermGuiSlot) scroll.getGuiPart(slotName);
            this.guiSlots.add(slot);
        }
    }

    /**
     * 获取暂存箱对象
     */
    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);
        }
    }

    synchronized public void setItemToPauseBox(ItemStack item){
//        if (!this.disassembleFlag){
//            return;
//        }
        for (int i = 0; i <= 15 ; i++){
            GermGuiSlot germGuiSlot = guiSlots.get(i);
            if (germGuiSlot.getItemStack().getType() == Material.AIR){
                germGuiSlot.setItemStack(item);
                return;
            }
        }
    }

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

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

    public void boolGui(){
        if (data.getId() != 0 && data.getTargetIndex() != null) {
            GermGuiCanvas bgCanvas = (GermGuiCanvas) this.getGuiPart("background");
            GermGuiSlot disassembleSlot = (GermGuiSlot) bgCanvas.getGuiPart("disassembleSlot");
            disassembleSlot.setInteract(false);
            //此处为获取分解的物品的item
            disassembleSlot.setItemStack(SrItemAPI.getItem(data.getTargetIndex(),
                    new HashMap<>(),null,true,true));

            GermGuiGif fire = (GermGuiGif) bgCanvas.getGuiPart("fire");
            GermGuiButton men1 = (GermGuiButton) bgCanvas.getGuiPart("men1");
            GermGuiTexture doorPause = (GermGuiTexture) bgCanvas.getGuiPart("doorPause");
            GermGuiGif door = (GermGuiGif) bgCanvas.getGuiPart("door");
            GermGuiLabel label = (GermGuiLabel) bgCanvas.getGuiPart("label");

            men1.setEnable(false);
            fire.setEnable(true);
            doorPause.setEnable(true);
            int calculateMinutesDifference = MinUtil.calculateMinutesDifference(data.getDisassembleTime());
            if (calculateMinutesDifference <= 0) {
                //执行语句说明分解完成
                this.disassembleComplete();
                if ((boolean)disassembleSlot.getInteract()){

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

            }else {
                ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
                List<String> texts = new ArrayList<>();
                texts.add("#C80800FF距离分解完成");
                texts.add("#ACDA70D6还有"+calculateMinutesDifference+"分钟");
                label.setTexts(texts);
                label.setEnable(true);
                executor.scheduleWithFixedDelay(() -> {
                    int nums = MinUtil.calculateMinutesDifference(data.getDisassembleTime());

                    String text = "##ACDA70D6还有"+nums+"分钟";
                    texts.remove(1);
                    texts.add(text);
                    label.setTexts(texts);

                    if (nums <= 0) {

//                        if(!this.disassembleFlag){
//                            executor.shutdown();
//                            return;
//                        }

                        //执行语句说明分解完成
                        this.disassembleComplete();
                        if ((boolean)disassembleSlot.getInteract()){

                            JdbcSqlClass.deleteData(data.getId());

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

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

            //0延迟，minTime分钟后执行



        }
    }


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

    }


    public void openPauseBox(){
        GermGuiCanvas bgCanvas = (GermGuiCanvas) this.getGuiPart("background");
        GermGuiButton germGuiButton = (GermGuiButton)bgCanvas.getGuiPart("pauseBoxButton");
        germGuiButton.registerCallbackHandler(((player, btn) -> {

            if (this.temporarilyBoxScreen.isOpened()){
                this.temporarilyBoxScreen.close();
            }else {
                this.temporarilyBoxScreen.openChildGui(this.playerHost);
            }

        }),GermGuiButton.EventType.LEFT_CLICK);
    }

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

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

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

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

    public void disassemble(Player player){
        GermGuiCanvas bgCanvas = (GermGuiCanvas) this.getGuiPart("background");
        GermGuiSlot disassembleSlot = (GermGuiSlot) bgCanvas.getGuiPart("disassembleSlot");
        if ((boolean)disassembleSlot.getInteract() == false){
            //正在分解某种物品
            return;
        }
        ItemStack itemStack = disassembleSlot.getItemStack();

        if (itemStack.getType() == Material.AIR || itemStack == null) {
            player.sendMessage(ChatColor.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(ChatColor.RED+"放入的物品不可分解!");
            return;
        }
        disassembleSlot.setInteract(false);//关闭交互

        int amount = itemStack.getAmount();
        if (amount > 1){
            ItemStack itemStack1 = itemStack.clone();
            itemStack1.setAmount(amount - 1);
            player.getInventory().addItem(itemStack1);
            player.sendMessage(ChatColor.GREEN+"多余的物品放进背包!");
        }

        itemStack.setAmount(1);

        disassembleSlot.setItemStack(itemStack);
        //上方if语句通过表示该物品可以分解
        //假如启动按钮是油壶，
        GermGuiGif door = (GermGuiGif) bgCanvas.getGuiPart("door");
        GermGuiTexture doorPause = (GermGuiTexture) bgCanvas.getGuiPart("doorPause");
        door.setCycle(1);
        door.setPause(14);
        if ((boolean)door.getEnable() == true){
            return;
        }
        GermGuiButton men1 = (GermGuiButton) bgCanvas.getGuiPart("men1");
        men1.setEnable(false);
        GermGuiGif fire = (GermGuiGif) bgCanvas.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();

        GermGuiLabel label = (GermGuiLabel) bgCanvas.getGuiPart("label");
        List<String> texts = new ArrayList<>();
        texts.add("#C80800FF距离分解完成");
        int minTime = MinUtil.calculateMinutesDifference(data.getDisassembleTime());
        texts.add("#ACDA70D6还有"+minTime+"分钟");
        label.setTexts(texts);
        label.setEnable(true);

        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(() -> {
            if (!doorPause.isEnable()){
                doorPause.setEnable(true);
            }
            if (door.isEnable()){
                door.setEnable(false);
            }
        },2,TimeUnit.SECONDS);

        executor.scheduleWithFixedDelay(() -> {
            int calculateMinutesDifference = MinUtil.calculateMinutesDifference(data.getDisassembleTime());
            String text = "#ACDA70D6还有"+calculateMinutesDifference+"分钟";
            texts.remove(1);
            texts.add(text);
            label.setTexts(texts);
            if (calculateMinutesDifference <= 0) {
                //执行语句说明分解完成
                label.setEnable(false);



                this.disassembleComplete();
                if ((boolean)disassembleSlot.getInteract()){

                    JdbcSqlClass.deleteData(data.getId());

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

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


    }

    /**
     * 此方法用于获取产物
     */
    public void disassembleComplete(){
        GermGuiCanvas bgCanvas = (GermGuiCanvas) this.getGuiPart("background");
        GermGuiSlot disassembleSlot = (GermGuiSlot) bgCanvas.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);
        //物品框置空，产物放在暂存箱中
        disassembleSlot.setItemStack(null);
        this.setItemToPauseBox(product);
//        GermGuiScroll germGuiScroll = (GermGuiScroll) this.temporarilyBoxScreen.getGuiPart("scroll");

    }

    //遍历gui的所有物品槽，并且返回到玩家背包中
    synchronized private void returnItemStacks(Player player) {
//        this.disassembleFlag = 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());
            }
        }

        for (GermGuiSlot guiPart : guiSlots) {
            if (guiPart.getItemStack().getType() != Material.AIR) {
                ItemStack itemStack = guiPart.getItemStack();
                SrItemHandler srItemHandler = ItemStackHelper.getSrItemHandler(itemStack);

                if (!srItemHandler.isSrItem()){
                    player.sendMessage(ChatColor.GREEN+"暂存箱只能存放RPG物品!");
                    player.getInventory().addItem(itemStack);
                    guiPart.setItemStack(null);
                    continue;
                }

                String index = srItemHandler.getLore().get(0);
                //\\.转义符号
                String[] split = index.split("\\.");
                String s = split[1];
                if (s.equals("equip")){
                    player.sendMessage(ChatColor.GREEN+"暂存箱只能存放材料和原胚物品!");
                    player.getInventory().addItem(itemStack);
                    guiPart.setItemStack(null);
                    continue;
                }

            }
        }
    }

}
