package com.acethewildfire.acesbs.effect;

import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectCategory;
import net.minecraft.entity.effect.StatusEffectInstance;

import java.util.Random;

public class JitteryEffect extends StatusEffect {
    protected JitteryEffect(StatusEffectCategory category, int color) {
        super(category, color);
    }

    Random r = new Random();
    int timer = 0;
    int maxTimer = 200;
    int delay = 200;
    int maxDelay = 20;
    int times = 2;

    @Override
    public boolean applyUpdateEffect(LivingEntity entity, int amplifier) {
        StatusEffectInstance effect = entity.getStatusEffect(ModEffects.JITTERY);
        if (effect == null) return true;

        if (timer >= maxTimer){
            //Time to do the jitterbug
            if (times <= 0){
                timer = 0;
                maxTimer = r.nextInt(100, 200);
                times = r.nextInt(2,5);
            } else if (delay >= maxDelay) {
                // Dance
                double randomVelocityX = r.nextDouble(-0.3, 0.3);
                double randomVelocityZ = r.nextDouble(-0.3, 0.3);
                entity.addVelocity(randomVelocityX, 0, randomVelocityZ);

                //Decrement times
                times--;

                //Set new delay
                delay = 0;
                maxDelay = r.nextInt(5, 10);
            } else {
                delay++;
            }
        } else {
            timer++;
        }

        // When 1 tick remains, it's about to end
        if (effect.getDuration() == 1 && !entity.getWorld().isClient()) {

            // Apply new effect
            entity.addStatusEffect(new StatusEffectInstance(
                    ModEffects.WITHDRAWAL,  // second effect
                    12000,                  // duration
                    0                       // amplifier
            ));
        }
        return true;
    }

    @Override
    public boolean canApplyUpdateEffect(int duration, int amplifier) {
        return true;
    }
}
