package studio.halbear.hem.procedures;

import studio.halbear.hem.entity.GiantButterflyWalkingEntity;
import studio.halbear.hem.HemMod;

import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.World;
import net.minecraft.world.IWorld;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.ResourceLocation;
import net.minecraft.tags.BlockTags;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.entity.SpawnReason;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ILivingEntityData;
import net.minecraft.entity.Entity;

import java.util.stream.Collectors;
import java.util.function.Function;
import java.util.Random;
import java.util.Map;
import java.util.List;
import java.util.Comparator;

public class GiantButterflyOnEntityTickUpdateProcedure {

	public static void executeProcedure(Map<String, Object> dependencies) {
		if (dependencies.get("world") == null) {
			if (!dependencies.containsKey("world"))
				HemMod.LOGGER.warn("Failed to load dependency world for procedure GiantButterflyOnEntityTickUpdate!");
			return;
		}
		if (dependencies.get("x") == null) {
			if (!dependencies.containsKey("x"))
				HemMod.LOGGER.warn("Failed to load dependency x for procedure GiantButterflyOnEntityTickUpdate!");
			return;
		}
		if (dependencies.get("y") == null) {
			if (!dependencies.containsKey("y"))
				HemMod.LOGGER.warn("Failed to load dependency y for procedure GiantButterflyOnEntityTickUpdate!");
			return;
		}
		if (dependencies.get("z") == null) {
			if (!dependencies.containsKey("z"))
				HemMod.LOGGER.warn("Failed to load dependency z for procedure GiantButterflyOnEntityTickUpdate!");
			return;
		}
		if (dependencies.get("entity") == null) {
			if (!dependencies.containsKey("entity"))
				HemMod.LOGGER.warn("Failed to load dependency entity for procedure GiantButterflyOnEntityTickUpdate!");
			return;
		}
		IWorld world = (IWorld) dependencies.get("world");
		double x = dependencies.get("x") instanceof Integer ? (int) dependencies.get("x") : (double) dependencies.get("x");
		double y = dependencies.get("y") instanceof Integer ? (int) dependencies.get("y") : (double) dependencies.get("y");
		double z = dependencies.get("z") instanceof Integer ? (int) dependencies.get("z") : (double) dependencies.get("z");
		Entity entity = (Entity) dependencies.get("entity");
		if (entity.getMotion().getY() > -0.15 && entity.getMotion().getX() < 0.015 && entity.getMotion().getZ() < 0.015
				&& entity.getMotion().getX() > -0.015 && entity.getMotion().getZ() > -0.015) {
			entity.setMotion((entity.getMotion().getX()), (entity.getMotion().getY() - 0.05), (entity.getMotion().getZ()));
		}
		if (BlockTags.getCollection().getTagByID(new ResourceLocation("forge:solid_block"))
				.contains((world.getBlockState(new BlockPos(x, y - 0.2, z))).getBlock()) && entity.getMotion().getX() == 0
				&& entity.getMotion().getZ() == 0) {
			if (world instanceof ServerWorld) {
				Entity entityToSpawn = new GiantButterflyWalkingEntity.CustomEntity(GiantButterflyWalkingEntity.entity, (World) world);
				entityToSpawn.setLocationAndAngles(x, y, z, (float) (entity.rotationYaw), (float) (entity.rotationPitch));
				entityToSpawn.setRenderYawOffset((float) (entity.rotationYaw));
				entityToSpawn.setRotationYawHead((float) (entity.rotationYaw));
				entityToSpawn.setMotion((entity.getMotion().getX()), (entity.getMotion().getY()), (entity.getMotion().getZ()));
				if (entityToSpawn instanceof MobEntity)
					((MobEntity) entityToSpawn).onInitialSpawn((ServerWorld) world, world.getDifficultyForLocation(entityToSpawn.getPosition()),
							SpawnReason.MOB_SUMMONED, (ILivingEntityData) null, (CompoundNBT) null);
				world.addEntity(entityToSpawn);
			}
			if (entity.isBeingRidden()) {
				{
					List<Entity> _entfound = world
							.getEntitiesWithinAABB(Entity.class,
									new AxisAlignedBB(x - (2 / 2d), y - (2 / 2d), z - (2 / 2d), x + (2 / 2d), y + (2 / 2d), z + (2 / 2d)), null)
							.stream().sorted(new Object() {
								Comparator<Entity> compareDistOf(double _x, double _y, double _z) {
									return Comparator.comparing((Function<Entity, Double>) (_entcnd -> _entcnd.getDistanceSq(_x, _y, _z)));
								}
							}.compareDistOf(x, y, z)).collect(Collectors.toList());
					for (Entity entityiterator : _entfound) {
						if (entityiterator instanceof ServerPlayerEntity && entityiterator.isPassenger()
								&& (entityiterator.getRidingEntity()) == entity) {
							entityiterator
									.startRiding(((Entity) world
											.getEntitiesWithinAABB(GiantButterflyWalkingEntity.CustomEntity.class, new AxisAlignedBB(x - (2 / 2d),
													y - (2 / 2d), z - (2 / 2d), x + (2 / 2d), y + (2 / 2d), z + (2 / 2d)), null)
											.stream().sorted(new Object() {
												Comparator<Entity> compareDistOf(double _x, double _y, double _z) {
													return Comparator
															.comparing((Function<Entity, Double>) (_entcnd -> _entcnd.getDistanceSq(_x, _y, _z)));
												}
											}.compareDistOf(x, y, z)).findFirst().orElse(null)));
							((Entity) world.getEntitiesWithinAABB(GiantButterflyWalkingEntity.CustomEntity.class,
									new AxisAlignedBB(x - (2 / 2d), y - (2 / 2d), z - (2 / 2d), x + (2 / 2d), y + (2 / 2d), z + (2 / 2d)), null)
									.stream().sorted(new Object() {
										Comparator<Entity> compareDistOf(double _x, double _y, double _z) {
											return Comparator.comparing((Function<Entity, Double>) (_entcnd -> _entcnd.getDistanceSq(_x, _y, _z)));
										}
									}.compareDistOf(x, y, z)).findFirst().orElse(null)).getPersistentData().putBoolean("DespawnImmune", (true));
						}
					}
				}
			}
			if (!entity.world.isRemote())
				entity.remove();
		}
		if (entity.isBeingRidden()) {
			if (entity.getPersistentData().getDouble("decisioncooldown") == 0) {
				entity.getPersistentData().putDouble("decisioncooldown", (MathHelper.nextInt(new Random(), 30, 120)));
				if (Math.random() >= 0.3) {
					entity.getPersistentData().putBoolean("move", (true));
				} else {
					entity.getPersistentData().putBoolean("move", (false));
				}
				if (Math.random() >= 0.5) {
					entity.getPersistentData().putDouble("goalyaw", (MathHelper.nextInt(new Random(), -360, 360)));
				}
			}
			if (!world.isAirBlock(new BlockPos(x + entity.getLookVec().x, y, z + entity.getLookVec().z))) {
				entity.rotationYaw = (float) ((entity.rotationYaw + 15));
				entity.setRenderYawOffset(entity.rotationYaw);
				entity.prevRotationYaw = entity.rotationYaw;
				if (entity instanceof LivingEntity) {
					((LivingEntity) entity).prevRenderYawOffset = entity.rotationYaw;
					((LivingEntity) entity).rotationYawHead = entity.rotationYaw;
					((LivingEntity) entity).prevRotationYawHead = entity.rotationYaw;
				}
				entity.rotationPitch = (float) ((entity.rotationPitch));
			}
			if (entity.getPersistentData().getBoolean("move")) {
				entity.setMotion((entity.getLookVec().x / 8), (entity.getMotion().getY()), (entity.getLookVec().z / 8));
			}
			if (entity.getPersistentData().getDouble("goalyaw") != entity.rotationYaw) {
				if (entity.getPersistentData().getDouble("goalyaw") > entity.rotationYaw + 11) {
					entity.rotationYaw = (float) ((entity.rotationYaw + 10));
					entity.setRenderYawOffset(entity.rotationYaw);
					entity.prevRotationYaw = entity.rotationYaw;
					if (entity instanceof LivingEntity) {
						((LivingEntity) entity).prevRenderYawOffset = entity.rotationYaw;
						((LivingEntity) entity).rotationYawHead = entity.rotationYaw;
						((LivingEntity) entity).prevRotationYawHead = entity.rotationYaw;
					}
					entity.rotationPitch = (float) ((entity.rotationPitch));
				} else if (entity.getPersistentData().getDouble("goalyaw") > entity.rotationYaw) {
					entity.rotationYaw = (float) ((entity.rotationYaw + 1));
					entity.setRenderYawOffset(entity.rotationYaw);
					entity.prevRotationYaw = entity.rotationYaw;
					if (entity instanceof LivingEntity) {
						((LivingEntity) entity).prevRenderYawOffset = entity.rotationYaw;
						((LivingEntity) entity).rotationYawHead = entity.rotationYaw;
						((LivingEntity) entity).prevRotationYawHead = entity.rotationYaw;
					}
					entity.rotationPitch = (float) ((entity.rotationPitch));
				}
				if (entity.getPersistentData().getDouble("goalyaw") < entity.rotationYaw - 11) {
					entity.rotationYaw = (float) ((entity.rotationYaw - 10));
					entity.setRenderYawOffset(entity.rotationYaw);
					entity.prevRotationYaw = entity.rotationYaw;
					if (entity instanceof LivingEntity) {
						((LivingEntity) entity).prevRenderYawOffset = entity.rotationYaw;
						((LivingEntity) entity).rotationYawHead = entity.rotationYaw;
						((LivingEntity) entity).prevRotationYawHead = entity.rotationYaw;
					}
					entity.rotationPitch = (float) ((entity.rotationPitch));
				} else if (entity.getPersistentData().getDouble("goalyaw") < entity.rotationYaw) {
					entity.rotationYaw = (float) ((entity.rotationYaw - 1));
					entity.setRenderYawOffset(entity.rotationYaw);
					entity.prevRotationYaw = entity.rotationYaw;
					if (entity instanceof LivingEntity) {
						((LivingEntity) entity).prevRenderYawOffset = entity.rotationYaw;
						((LivingEntity) entity).rotationYawHead = entity.rotationYaw;
						((LivingEntity) entity).prevRotationYawHead = entity.rotationYaw;
					}
					entity.rotationPitch = (float) ((entity.rotationPitch));
				}
			}
			entity.getPersistentData().putDouble("decisioncooldown", (entity.getPersistentData().getDouble("decisioncooldown") - 1));
		}
	}
}
