package com.thebrokenrail.herobrine.entity.ai.stage;

import com.thebrokenrail.herobrine.config.HardcodedConfig;
import com.thebrokenrail.herobrine.entity.HerobrineEntity;
import com.thebrokenrail.herobrine.entity.ai.AIStage;
import net.minecraft.entity.Entity;
import net.minecraft.entity.TntEntity;
import net.minecraft.entity.projectile.ExplosiveProjectileEntity;
import net.minecraft.entity.projectile.FireballEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.GameRules;

public class FireballStage extends AIStage {
    private int time = 0;
    private Entity entity = null;

    public FireballStage(HerobrineEntity entity) {
        super(entity);
    }

    @Override
    public void tick() {
        getEntity().getDataTracker().set(HerobrineEntity.POSE, HerobrineEntity.Pose.FIREBALL);

        if (entity != null) {
            updatePosition();
        }
        if (time < HardcodedConfig.HEROBRINE_FIREBALL_TIME) {
            time++;
        } else if (entity == null) {
            time = 0;

            if (getEntity().getRandom().nextBoolean() && getEntity().getEntityWorld().getGameRules().getBoolean(GameRules.DO_MOB_GRIEFING)) {
                entity = new TntEntity(getEntity().getEntityWorld(), 0, 0, 0, getEntity());
                getEntity().playSound(SoundEvents.ITEM_FLINTANDSTEEL_USE);
            } else {
                entity = new FireballEntity(getEntity().getEntityWorld(), getEntity(), 0, 0, 0);
                ((FireballEntity) entity).explosionPower = 4;
                getEntity().playSound(SoundEvents.ENTITY_GHAST_SHOOT);
            }
            entity.setNoGravity(true);

            updatePosition();

            getEntity().getEntityWorld().spawnEntity(entity);
        } else {
            time = 0;

            Vec3d pos = getEntity().getRotationVec(1.0f);
            entity.setVelocity(pos);
            if (entity instanceof FireballEntity) {
                ((ExplosiveProjectileEntity) entity).posX = pos.getX() * 0.3d;
                ((ExplosiveProjectileEntity) entity).posY = pos.getY() * 0.3d;
                ((ExplosiveProjectileEntity) entity).posZ = pos.getZ() * 0.3d;
            }
            entity.setNoGravity(false);

            nextStage();
        }
    }

    private void updatePosition() {
        Vec3d pos = getEntity().getRotationVec(1.0f).add(getEntity().getPos());
        entity.updatePosition(pos.getX(), pos.getY(), pos.getZ());
        entity.setVelocity(0, 0, 0);
    }

    @Override
    public void fromTag(CompoundTag tag) {
        time = tag.getInt("Time");
        entity = getEntity().getServerWorld().getEntity(tag.getUuid("Entity"));
    }

    @Override
    public CompoundTag toTag() {
        CompoundTag tag = new CompoundTag();
        tag.putUuid("Entity", entity.getUuid());
        tag.putInt("Time", time);
        return tag;
    }
}
