package com.yaohun.wheatwar.effect;

import com.yaohun.wheatwar.WheatWar;
import com.yaohun.wheatwar.game.Game;
import com.yaohun.wheatwar.listener.GameListener;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.*;
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 SummonTheBombsTNT {

    public static void apply(Game game, Player zhubo, String userName, int amount) {
        if (!game.isStarted()) {
            return;
        }
        // 获取主播的uuid
        UUID uuid = zhubo.getUniqueId();
        // 计时器key
        String timepieceKey = "SummonBombsTNTEffect";
        startTimepieceEvent(game,zhubo,userName,timepieceKey);
        if(CDTimeAPI.isCD(uuid,timepieceKey)){
            long newTime = CDTimeAPI.getCD(uuid,timepieceKey) + (195L * amount);
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,newTime);
        } else {
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,195L * 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;
                }
                zhubo.playSound(zhubo.getLocation(), Sound.ENTITY_CHICKEN_EGG,1,1);
                spawnMobs(game);
            }
        }.runTaskTimer(WheatWar.inst(), 0L, 4L);
        game.addTasks(task);
    }

    public static void spawnMobs(Game game) {
        for (Entity entity : game.getWorld().getEntities()){
            if (entity instanceof ZombieVillager || entity instanceof Zombie) {
                if(entity.getPassengers().size() <= 0) {
                    // 在僵尸头上生成TNT
                    TNTPrimed tnt = (TNTPrimed) entity.getWorld().spawn(entity.getLocation().add(0, 2, 0), TNTPrimed.class);
                    GameListener.whiteListTNT.add(tnt.getUniqueId());
                    // 设置爆炸范围和伤害监听器
                    tnt.setYield(2.0F); // 爆炸范围（默认值为 4.0F）
                    tnt.setIsIncendiary(false); // 如果需要爆炸引起火焰，可设置为 true
                    tnt.setFuseTicks(40); // 设置2秒后爆炸（1秒=20 ticks）
                    // 将TNT附加在僵尸头上
                    entity.addPassenger(tnt);
                    break;
                }
            }
        }
    }
}
