package com.yaohun.demonskills.core;

import com.yaohun.demonskills.SkillsMain;
import com.yaohun.demonskills.config.Config;
import com.yaohun.demonskills.config.MessageUtil;
import com.yaohun.demonskills.data.SkillData;
import com.yaohun.demonskills.manage.SkillManager;
import me.Demon.DemonPlugin.DemonAPI;
import me.Demon.DemonPlugin.data.NbtItem;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

public class SkillStoneUpgrade {

    public static void carryOut(Player player,boolean upgradeMode){
        ItemStack itemStack = player.getInventory().getItemInMainHand();
        if(DemonAPI.itemIsNull(itemStack) || DemonAPI.itemIsLore(itemStack)){
            MessageUtil.sendMessage(player, Config.langData.getMessage("handItemError"),Sound.ENTITY_VILLAGER_NO);
            return;
        }
        NbtItem nbtItem = new NbtItem(itemStack);
        if(!nbtItem.hasKey("skillName")){
            MessageUtil.sendMessage(player, Config.langData.getMessage("handItemError"),Sound.ENTITY_VILLAGER_NO);
            return;
        }
        if(upgradeMode){
            int levelLimit = 10;
            int skillLevel = nbtItem.getInteger("skillLevel") + 1;
            if(skillLevel > levelLimit){
                MessageUtil.sendMessage(player, Config.langData.getMessage("handItemError").replace("{levelLimit}",String.valueOf(levelLimit)),Sound.ENTITY_VILLAGER_NO);
                return;
            }
            player.getInventory().setItemInMainHand(upgradeLevel(nbtItem));
        } else {
            player.getInventory().setItemInMainHand(reduceLevel(nbtItem));
        }
    }

    private static ItemStack upgradeLevel(NbtItem nbtItem){
        String playerName = nbtItem.getString("skillOwner");
        String skillName = nbtItem.getString("skillName");
        int skillLevel = nbtItem.getInteger("skillLevel") + 1;
        SkillData skillData = SkillManager.skillDataMap.get(skillName);
        return skillData.getItemStack(playerName, skillLevel);
    }

    private static ItemStack reduceLevel(NbtItem nbtItem){
        String playerName = nbtItem.getString("skillOwner");
        String skillName = nbtItem.getString("skillName");
        int skillLevel = nbtItem.getInteger("skillLevel") - 1;
        SkillData skillData = SkillManager.skillDataMap.get(skillName);
        return skillData.getItemStack(playerName, Math.max(1, skillLevel));
    }
}
