package com.yaohun.demonskills.component.damage;

import com.yaohun.demonskills.SkillsMain;
import com.yaohun.demonskills.api.SkillComponent;
import com.yaohun.demonskills.api.TargetSelector;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

public class DamageContinuedComponent implements SkillComponent {

    private final double hurtValue;
    private final TargetSelector selector;
    private final int numberCount;
    private final long delayTicks;
    private double radius = 10;

    public DamageContinuedComponent(double hurtValue, TargetSelector selector, int numberCount,long delayTicks) {
        this.hurtValue = hurtValue;
        this.selector = selector;
        this.numberCount = numberCount;
        this.delayTicks = delayTicks;
    }

    public DamageContinuedComponent(double hurtValue, TargetSelector selector, int numberCount,long delayTicks, double radius) {
        this.hurtValue = hurtValue;
        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;
                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;
                        }
                        living.damage(hurtValue, caster);
                    }
                }.runTaskTimer(SkillsMain.inst(),0L, delayTicks);
            }
        }
    }
}
