package com.yaohun.wheatwar.effect;

import com.yaohun.wheatwar.WheatWar;
import com.yaohun.wheatwar.game.Game;
import net.minecraft.world.entity.EntityInsentient;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Particle;
import org.bukkit.block.Block;
import org.bukkit.block.data.Ageable;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_18_R2.entity.CraftLivingEntity;
import org.bukkit.entity.Cow;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import tools.CDTimeAPI;

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

public class SummonTheCow {

    public static void apply(Game game, Player zhubo, String userName, int amount) {
        if (!game.isStarted()) {
            return;
        }
        // 获取主播的uuid
        UUID uuid = zhubo.getUniqueId();
        // 计时器key
        String timepieceKey = "SummonCowEffect";
        startTimepieceEvent(game,zhubo,userName,timepieceKey);
        if(CDTimeAPI.isCD(uuid,timepieceKey)){
            long newTime = CDTimeAPI.getCD(uuid,timepieceKey) + (95L * amount);
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,newTime);
        } else {
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,95L * amount);
        }
    }

    public static void startTimepieceEvent(Game game, Player zhubo, String userName, String timepieceKey) {
        if (CDTimeAPI.isCD(zhubo.getUniqueId(), timepieceKey)) {
            return;
        }
        BukkitTask task = new BukkitRunnable() {
            @Override
            public void run() {
                if (!CDTimeAPI.isCD(zhubo.getUniqueId(), timepieceKey)) {
                    cancel();
                    return;
                }
                spawnMobs(game,userName);
            }
        }.runTaskTimer(WheatWar.inst(), 0L, 2L);
        game.addTasks(task);
    }

    public static HashMap<UUID, Location> locationMap = new HashMap<>(); // 村民 正在执行的任务 需前往的地方

    public static void spawnMobs(Game game,String userName) {
        Location location = game.getFarmlandRandom().clone().add(0,1,0);
        Cow entity = (Cow) location.getWorld().spawnEntity(location, EntityType.COW);
        entity.setCollidable(false);
        entity.setCustomNameVisible(true);
        entity.setCustomName("§c" + userName);
        Location centralPoint = game.getCentralPoint();
        // 计算方向
        Vector direction = centralPoint.toVector().subtract(location.toVector()).normalize();
        // 设置初速度
        double initialVerticalVelocity = 0.4; // 向上抛的速度
        double horizontalVelocity = 1.35; // 控制水平抛出的力度
        // 创建一个向量，包括水平和垂直方向的速度
        Vector velocity = direction.multiply(horizontalVelocity).setY(initialVerticalVelocity);
        entity.setVelocity(velocity);
        new BukkitRunnable() {
            private int i = 0;
            @Override
            public void run() {
                if(i >= 15){
                    cancel();
                    return;
                }
                game.getWorld().spawnParticle(Particle.ELECTRIC_SPARK,entity.getLocation().clone().add(0,1,0),2);
                //game.getWorld().spawnParticle(Particle.VILLAGER_HAPPY,entity.getLocation().clone().add(0,1,0),2);
                i++;
            }
        }.runTaskTimer(WheatWar.inst(),0,1L);
        new BukkitRunnable() {
            private int amount = 10;
            @Override
            public void run() {
                UUID uuid = entity.getUniqueId();
                // 若村民死亡则计时器种植并结束村民任务
                if (entity.isDead()) {
                    locationMap.remove(uuid);
                    cancel();
                    return;
                }
                if(amount <= 0){
                    entity.damage(999.0D);
                    cancel();
                    return;
                }
                // 检测村民是否存在任务  若存在则抵达目标方块时触发消息  ”已完成任务“
                //
                // 若村民没有任务则获取坐标后通过NMS设置村民寻路目标坐标 并put添加任务
                if (locationMap.containsKey(uuid)) {
                    Location location1 = locationMap.get(uuid);
                    if (entity.getLocation().distance(location1) <= 1.0) {
                        amount--;
                        //到达目标小麦位置
                        locationMap.remove(uuid);
                        // 获取这个坐标的方块数据是未种小麦还是未成熟小麦
                        Block block = location.getWorld().getBlockAt(location1);
                        if(!block.getType().equals(Material.AIR)) {
                            if (block.getType().equals(Material.WHEAT)) {
                                BlockData blockData = block.getBlockData();
                                if (blockData instanceof Ageable ageable) {
                                    if (ageable.getAge() == 7) {
                                        ageable.setAge(3);
                                        block.setBlockData(ageable);
                                    } else {
                                        block.setType(Material.AIR);
                                    }
                                    block.getWorld().spawnParticle(Particle.VILLAGER_ANGRY, block.getLocation().add(0.5, 1, 0.5), 5, 0.5, 0.5, 0.5, 0.1);
                                }
                            }
                        }
                    } else {
                        Vector direction = location1.toVector().subtract(entity.getLocation().toVector()).normalize();
                        Vector velocity = direction.multiply(0.25);
                        entity.setVelocity(velocity);
                    }
                } else {
                    // 优先寻找未种小麦的地    已种小麦未成熟的地  坐标
                    Location location1 = game.getPriorityClearLocation();
                    if(location1 == null){
                        Bukkit.broadcastMessage("！游戏结束！路人获胜！");
                        cancel();
                        return;
                    }
                    EntityInsentient nmsEntity = (EntityInsentient) ((CraftLivingEntity) entity).getHandle();
                    nmsEntity.D().a(location1.getX(), location1.getY(), location1.getZ(), 1.0F);
                    locationMap.put(uuid, location1);
                    entity.setCustomName("§c" + userName+" [§6"+amount+"§c]");
                }
            }
        }.runTaskTimer(WheatWar.inst(), 20L, 1L);
    }
}
