package com.yaohun.wheatwar.listener;

import com.yaohun.wheatwar.effect.SummonTheZombie;
import org.bukkit.Bukkit;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityTargetEvent;

import java.util.HashMap;
import java.util.UUID;

public class GameListener implements Listener {

    public static HashMap<UUID,UUID> zombieTargetMap = new HashMap<>();
    @EventHandler
    public void onZombieTarget(EntityTargetEvent event) {
        // 检查是否是僵尸
        if (event.getEntityType() == EntityType.ZOMBIE) {
            // 检查目标是否是玩家
            if (event.getTarget() instanceof Player) {
                // 取消该事件以阻止僵尸将玩家设为仇恨目标
                event.setCancelled(true);
            }
            if(event.getTarget() instanceof Villager villager){
                UUID vuuid = villager.getUniqueId();
                UUID uuid = event.getEntity().getUniqueId();
                /*// 若这个村民已经被僵尸锁定则无法被选中
                if(zombieTargetMap.containsKey(vuuid)){
                    event.setCancelled(true);
                } else {
                    zombieTargetMap.put(vuuid,uuid);
                }*/
            }
        }
    }

    @EventHandler
    public void ondeath(EntityDeathEvent e){
        // 检查被杀的实体是否是村民
        if (e.getEntity() instanceof Villager villager) {
            // 检查村民是否是被僵尸杀死的
            if (villager.getLastDamageCause() instanceof EntityDamageByEntityEvent damageEvent) {
                if (damageEvent.getDamager() instanceof Zombie zombie) {
                    HashMap<UUID, Integer> zombieKillMap = SummonTheZombie.zombieKillMap;
                    if(zombieKillMap.get(zombie.getUniqueId()) != null){
                        int newAmount = zombieKillMap.get(zombie.getUniqueId()) - 1;
                        if(newAmount >= 1){
                            SummonTheZombie.zombieKillMap.put(zombie.getUniqueId(),newAmount);
                        } else {
                            zombie.damage(999.0D);
                        }
                    }
                }
            }
        }
    }

}
