package com.yutian.minerwar.effects;

import com.yutian.minerwar.MinerWar;
import com.yutian.minerwar.game.Game;
import org.bukkit.Location;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import tools.CDTimeAPI;
import tools.RandomUtil;

import java.util.Random;
import java.util.UUID;

public class ShoutArrow {

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

    public static void startTimepieceEvent(Game game,Player zhubo,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;
                }
                spawnArrowAroundPlayer(zhubo,5);
            }
        }.runTaskTimer(MinerWar.inst(), 0L, 5L);
        game.addTasks(task);
    }

    public static void spawnArrowAroundPlayer(Player player, double radius) {
        Random random = new Random();
        Location playerLocation = player.getLocation();
        // 生成一个随机的圆周位置
        double angle = 2 * Math.PI * random.nextDouble(); // 随机角度
        double x = radius * Math.cos(angle); // 随机 x
        double z = radius * Math.sin(angle); // 随机 z
        // 获取随机位置
        Location randomLocation = playerLocation.clone().add(x, RandomUtil.getRandomInt(0,2), z);
        // 创建箭矢
        Arrow arrow = (Arrow) player.getWorld().spawnEntity(randomLocation, EntityType.ARROW);
        // 计算箭矢的朝向
        Vector direction = playerLocation.toVector().subtract(randomLocation.toVector()).normalize();
        // 设置箭矢的方向
        arrow.setVelocity(direction.multiply(3)); // 2 是箭矢的速度，可以调整
        arrow.setPersistent(true); // 设置箭矢的持久性
        arrow.setPickupStatus(Arrow.PickupStatus.DISALLOWED); // 禁止拾取箭矢
    }
}
