package land.chipmunk.chipmunkmod.mixin;

import land.chipmunk.chipmunkmod.modules.CommandCore;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(ClientPlayerEntity.class)
public abstract class ClientPlayerEntityMixin extends Entity {
    @Shadow @Final public ClientPlayNetworkHandler networkHandler;

    public ClientPlayerEntityMixin(final EntityType<?> type, final World world) {
        super(type, world);
    }

    @Inject(at = @At("TAIL"), method = "move")
    public void move(CallbackInfo ci) {
        final BlockPos origin = CommandCore.INSTANCE.origin;
        if (origin == null) {
            CommandCore.INSTANCE.move(this.getPos());
            return;
        }

        final int distanceSquared = this.getChunkPos().getSquaredDistance(new ChunkPos(origin));
        final int distance = (int) Math.sqrt(distanceSquared);

        if (distance > networkHandler.getWorld().getSimulationDistance()) {
            CommandCore.INSTANCE.clientPlayerEntityFilled = true;
            CommandCore.INSTANCE.move(this.getPos());
        }
    }
}
