package com.acethewildfire.acesbs.mixin;

import com.acethewildfire.acesbs.entity.ModEntities;
import com.acethewildfire.acesbs.util.CreeperTransformAccess;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(CreeperEntity.class)
public class CreeperTickMixin {

    @Inject(method = "tick", at = @At("HEAD"))
    private void tick(CallbackInfo ci) {
        CreeperEntity creeper = (CreeperEntity)(Object) this;
        CreeperTransformAccess access = (CreeperTransformAccess) creeper;

        if (!access.aces_bravo_sierra_template_1_21$isTransforming()) return;

        World world = creeper.getWorld();

        ((ServerWorld) world).spawnParticles(
                ParticleTypes.ENCHANT,
                creeper.getX(),
                creeper.getY() + 1.0,
                creeper.getZ(),
                5,     // count
                0.2,   // dx
                0.2,   // dy
                0.2,   // dz
                0.0    // speed
        );

        // timer
        int t = access.aces_bravo_sierra_template_1_21$getTransformTimer() + 1;
        access.aces_bravo_sierra_template_1_21$setTransformTimer(t);

        if (t >= 20 && !world.isClient) {

            world.playSound(null, creeper.getBlockPos(),
                    SoundEvents.ENTITY_ZOMBIE_VILLAGER_CURE,
                    creeper.getSoundCategory(), 1f, 1f);

            ((ServerWorld) world).spawnParticles(
                    ParticleTypes.EXPLOSION,
                    creeper.getX(),
                    creeper.getY() + 1.0,
                    creeper.getZ(),
                    5,     // count
                    0.2,   // dx
                    0.2,   // dy
                    0.2,   // dz
                    0.0    // speed
            );

            // spawn new mob
            MobEntity newMob = ModEntities.FREN.create(world);
            if (newMob != null) {
                Vec3d pos = creeper.getPos();
                newMob.refreshPositionAndAngles(pos.x, pos.y, pos.z, creeper.getYaw(), creeper.getPitch());
                world.spawnEntity(newMob);
                newMob.refreshPositionAndAngles(pos.x, pos.y, pos.z, creeper.getYaw(), creeper.getPitch());
            }

            creeper.discard();
        }
    }
}
