package com.yaohun.demonskills.listener;

import com.yaohun.demonskills.SkillsMain;
import com.yaohun.demonskills.gui.SkillsGui;
import com.yaohun.demonskills.manage.PlayerManager;
import com.yaohun.demonskills.util.CDTimeAPI;
import eos.moe.dragoncore.api.event.KeyPressEvent;
import eos.moe.dragoncore.api.event.KeyReleaseEvent;
import me.Demon.DemonPlugin.DemonAPI;
import me.Demon.DemonPlugin.data.NbtItem;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.serverct.ersha.jd.S;

import java.util.UUID;

public class PlayerListener implements Listener {

    @EventHandler
    public void onDamage(EntityDamageEvent e) {
        if (e.getEntity() instanceof Player) {
            Player player = (Player) e.getEntity();
            UUID uuid = player.getUniqueId();
            if(e.getCause() == EntityDamageEvent.DamageCause.FALL) {
                if(CDTimeAPI.isCD(uuid,"anti_fall")){
                    e.setCancelled(true);
                }
            }
        }
    }

    @EventHandler
    public void onImmunityDamage(EntityDamageByEntityEvent e){
        if(e.getEntity() instanceof Player){
            UUID uuid = e.getEntity().getUniqueId();
            if(CDTimeAPI.isCD(uuid,"skill_ImmunityDamage")){
                e.setCancelled(true);
            }
        }
    }


    @EventHandler
    public void onMutual(PlayerInteractEvent e) {
        if (e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
            if (e.getHand().equals(EquipmentSlot.HAND)) {
                Player player = e.getPlayer();
                ItemStack stack = player.getInventory().getItemInMainHand();
                if (!DemonAPI.itemIsNull(stack) && !DemonAPI.itemIsLore(stack)) {
                    NbtItem nbtItem = new NbtItem(stack);
                    if (nbtItem.hasKey("skillName")) {
                        String skillName = nbtItem.getString("skillName");
                        SkillsGui.OpenGui(player);
                        player.playSound(player.getLocation(), Sound.BLOCK_COMPARATOR_CLICK, 1, 1);
                    }
                }
            }
        }
    }

    @EventHandler
    public void onQuieSave(PlayerQuitEvent e){
        Player player = e.getPlayer();
        String playerName = player.getName();
        PlayerManager playerManager = SkillsMain.getPlayerManager();
        playerManager.getPlayerData(playerName).SavePlayerData();
    }
}
