package com.yutian.minerwar.effects;

import com.yutian.minerwar.MinerWar;
import com.yutian.minerwar.game.Game;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import tools.CDTimeAPI;

import java.util.UUID;

public class PotionBlindness {

    public static void apply(Game game, Player zhubo, int seconds){
        // 检测游戏是否启动
        if(!game.isStarted()){return;}
        // 获取主播的uuid
        UUID uuid = zhubo.getUniqueId();
        // 计时器key
        String timepieceKey = "turnOffTheLight";
        startTimepieceEvent(game,zhubo,timepieceKey);
        if(CDTimeAPI.isCD(uuid,timepieceKey)){
            long newTime = CDTimeAPI.getCD(uuid,timepieceKey) + (1000L * seconds);
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,newTime);
        } else {
            CDTimeAPI.setPlayerCD(uuid,timepieceKey,1000L * seconds);
        }
        double effectTime = (CDTimeAPI.getCD(uuid,timepieceKey) / 1000.0) * 20;
        // 获取现有致盲效果
        PotionEffect existingEffect = zhubo.getPotionEffect(PotionEffectType.BLINDNESS);
        if (existingEffect != null) {
            zhubo.removePotionEffect(PotionEffectType.BLINDNESS);
        }
        PotionEffect newEffect = new PotionEffect(PotionEffectType.BLINDNESS, (int) effectTime, 1); // 持续6秒（6 * 20ticks）
        zhubo.addPotionEffect(newEffect);
    }

    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)) {
                    zhubo.removePotionEffect(PotionEffectType.BLINDNESS);
                    zhubo.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 5, 1));
                    zhubo.playSound(zhubo.getLocation(), Sound.ENTITY_PLAYER_LEVELUP,1,1);
                    cancel();
                    return;
                }

                PotionEffect existingEffect = zhubo.getPotionEffect(PotionEffectType.BLINDNESS);
                if (existingEffect != null) {
                    // 如果已经有致盲效果，则延长其持续时间
                    int newDuration = existingEffect.getDuration();
                    if(newDuration <= 20){
                        zhubo.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 100, 1));
                    }
                } else {
                    zhubo.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 100, 1));
                }
            }
        }.runTaskTimer(MinerWar.inst(), 0L, 10L);
        game.addTasks(task);
    }
}
