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.EntityType;
import net.minecraft.entity.LightningEntity;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.Heightmap;

public class LightningStage extends AIStage {
    private int time = 0;
    private int max_time;

    public LightningStage(HerobrineEntity entity) {
        super(entity);
        max_time = getEntity().getRandom().nextInt((HardcodedConfig.HEROBRINE_LIGHTNING_MAX_TIME + 1) - HardcodedConfig.HEROBRINE_LIGHTNING_MIX_TIME) + HardcodedConfig.HEROBRINE_LIGHTNING_MIX_TIME;
    }

    @Override
    public void tick() {
        if (time >= max_time) {
            nextStage();
        } else {
            time++;

            getEntity().getDataTracker().set(HerobrineEntity.POSE, HerobrineEntity.Pose.LIGHTNING);

            if ((time & 2) == 0) {
                int x = getEntity().getRandom().nextInt(HardcodedConfig.HEROBRINE_LIGHTNING_RANGE + 1);
                int z = getEntity().getRandom().nextInt(HardcodedConfig.HEROBRINE_LIGHTNING_RANGE + 1);
                x = x - HardcodedConfig.HEROBRINE_LIGHTNING_RANGE / 2;
                z = z - HardcodedConfig.HEROBRINE_LIGHTNING_RANGE / 2;
                x = x + (int) getEntity().getX();
                z = z + (int) getEntity().getZ();
                int y = getEntity().getEntityWorld().getTopY(Heightmap.Type.WORLD_SURFACE, x, z);

                Vec3d pos = new Vec3d(x + 0.5d, y, z + 0.5d);

                LightningEntity lightning = new LightningEntity(EntityType.LIGHTNING_BOLT, getEntity().getEntityWorld());
                lightning.setCosmetic(true);
                lightning.updatePosition(pos.getX(), pos.getY(), pos.getZ());
                getEntity().getEntityWorld().spawnEntity(lightning);

                if (getEntity().getRandom().nextDouble() <= HardcodedConfig.HEROBRINE_LIGHTNING_ENTITY_CHANCE) {
                    EntityType<?> entityType = HardcodedConfig.HEROBRINE_LIGHTNING_ENTITIES[getEntity().getRandom().nextInt(HardcodedConfig.HEROBRINE_LIGHTNING_ENTITIES.length)];
                    Entity entity = entityType.create(getEntity().getEntityWorld());
                    assert entity != null;
                    entity.updatePosition(pos.getX(), pos.getY(), pos.getZ());
                    getEntity().getEntityWorld().spawnEntity(entity);
                }
            }
        }
    }

    @Override
    public void fromTag(CompoundTag tag) {
        time = tag.getInt("Time");
        max_time = tag.getInt("MaxTime");
    }

    @Override
    public CompoundTag toTag() {
        CompoundTag data = new CompoundTag();
        data.putInt("Time", time);
        data.putInt("MaxTime", max_time);
        return data;
    }
}
