package com.yaohun.demonskills.component.dragoncore;

import com.yaohun.demonskills.SkillsMain;
import com.yaohun.demonskills.api.SkillComponent;
import com.yaohun.demonskills.api.TargetSelector;
import com.yaohun.demonskills.util.RandomUtil;
import eos.moe.dragoncore.network.PacketSender;
import org.bukkit.Particle;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.UUID;

public class ParticleSpawnContinuedComponent implements SkillComponent {

    private final String particleName;
    private final TargetSelector selector;
    private final int numberCount;
    private final long delayTicks;
    private double radius = 3;

    public ParticleSpawnContinuedComponent(String particleName, TargetSelector selector, int numberCount, long delayTicks) {
        this.particleName = particleName;
        this.selector = selector;
        this.numberCount = numberCount;
        this.delayTicks = delayTicks;
    }

    public ParticleSpawnContinuedComponent(String particleName, TargetSelector selector, int numberCount, long delayTicks, double radius) {
        this.particleName = particleName;
        this.selector = selector;
        this.numberCount = numberCount;
        this.delayTicks = delayTicks;
        this.radius = radius;
    }

    @Override
    public void execute(Player caster) {
        for (Entity target : selector.selectTargets(caster)) {
            if (target instanceof LivingEntity) {
                LivingEntity living = (LivingEntity) target;
                UUID entityUUID = living.getUniqueId();
                new BukkitRunnable() {
                    int count = numberCount;
                    @Override
                    public void run() {
                        if (!living.getWorld().equals(caster.getWorld()) ||
                                living.getLocation().distance(caster.getLocation()) > radius) {
                            cancel();
                            return;
                        }
                        if(count-- < 0){
                            cancel();
                            return;
                        }
                        if(particleName.contains("Particle#")){
                            Particle particle = Particle.valueOf(particleName.replace("Particle#", ""));
                            caster.getWorld().spawnParticle(particle, RandomUtil.getRandomLocation(caster,radius), 5, 0, 0, 0, 0);
                        } else {
                            String particleUUID = UUID.randomUUID().toString();
                            PacketSender.addParticle(caster, particleName + ".particle", particleUUID, entityUUID.toString(), "0,0,0", 100);
                        }
                    }
                }.runTaskTimer(SkillsMain.inst(),0L, delayTicks);
            }
        }
    }
}
