package me.km;

import com.mojang.blaze3d.matrix.MatrixStack;
import java.awt.Color;
import me.km.blocks.ModBlocks;
import me.km.blocks.cookingpot.TileEntityCookingPot;
import me.km.items.ItemColoredSoup;
import me.km.items.ItemGemStone;
import me.km.items.ModItems;
import me.km.items.ModelCylinder;
import me.km.items.ModelHat;
import me.km.networking.ItemStackDisplayGui;
import me.km.networking.KeyManager;
import me.km.networking.ModPacketHandler;
import me.km.networking.PlayerDisplayGui;
import me.km.networking.PlayerHeadGui;
import me.km.networking.StatusDisplayGui;
import me.km.utils.ClientReflectionUtils;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.screen.MainMenuScreen;
import net.minecraft.client.gui.screen.MultiplayerScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.renderer.color.IBlockColor;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraft.client.renderer.entity.EntityRenderer;
import net.minecraft.client.renderer.entity.EntityRendererManager;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity;
import net.minecraft.item.BlockItem;
import static net.minecraft.item.ItemModelsProperties.registerProperty;
import net.minecraft.item.ItemStack;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Matrix4f;
import net.minecraft.util.math.vector.Vector3f;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.world.GameType;
import net.minecraft.world.GrassColors;
import net.minecraft.world.biome.BiomeColors;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderNameplateEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event;

@OnlyIn(Dist.CLIENT)
public class Client {

    public final static ModelCylinder CYLINDER = new ModelCylinder(1.0f);
    public final static ModelHat STRAW_HAT = new ModelHat(1.0f);
    public static KeyManager keyManager = null;

    public static void init() {
        MinecraftForge.EVENT_BUS.register(new Client());
        keyManager = new KeyManager();
        MinecraftForge.EVENT_BUS.register(keyManager);
        registerColors();
    }

    private static void registerColors() {
        RenderTypeLookup.setRenderLayer(ModBlocks.lantern, RenderType.getTranslucent());
        RenderTypeLookup.setRenderLayer(ModBlocks.tallGrass, RenderType.getCutout());
        RenderTypeLookup.setRenderLayer(ModBlocks.cherrySapling, RenderType.getCutout());
        RenderTypeLookup.setRenderLayer(ModBlocks.apricotSapling, RenderType.getCutout());
        RenderTypeLookup.setRenderLayer(ModBlocks.pearSapling, RenderType.getCutout());
        RenderTypeLookup.setRenderLayer(ModBlocks.plumSapling, RenderType.getCutout());
        RenderTypeLookup.setRenderLayer(ModBlocks.cherryLeaves, RenderType.getCutoutMipped());
        RenderTypeLookup.setRenderLayer(ModBlocks.apricotLeaves, RenderType.getCutoutMipped());
        RenderTypeLookup.setRenderLayer(ModBlocks.pearLeaves, RenderType.getCutoutMipped());
        RenderTypeLookup.setRenderLayer(ModBlocks.plumLeaves, RenderType.getCutoutMipped());

        BlockColors bColors = Minecraft.getInstance().getBlockColors();
        bColors.register((state, w, pos, tintIndex) -> {
            if(w == null || pos == null) {
                return -16777216;
            }
            TileEntityCookingPot tile = (TileEntityCookingPot) w.getTileEntity(pos);
            if(tile == null) {
                return -16777216;
            }
            Color c = tile.getColor();
            return -16777216 | c.getRed() << 16 | c.getGreen() << 8 | c.getBlue();
        }, ModBlocks.cookingPotCopper);

        IBlockColor tallGrass = (state, w, pos, tintIndex) -> {
            if(w != null && pos != null) {
                return BiomeColors.getGrassColor(w, pos);
            }
            return GrassColors.get(0.5D, 1.0D);
        };
        bColors.register(tallGrass, ModBlocks.tallGrass);

        ItemColors iColors = Minecraft.getInstance().getItemColors();
        iColors.register((stack, tintIndex) -> tintIndex > 0 ? -1 : ItemColoredSoup.getColor(stack),
                ModItems.coloredSoup);
        iColors.register(
                (stack, tintIndex) -> tintIndex > 0 ? -1
                        : ((ItemGemStone) stack.getItem()).getColor(stack),
                ModItems.gemStone, ModItems.rawGemStone, ModItems.flawlessGemStone);

        iColors.register((stack, tintIndex) -> tallGrass.getColor(
                ((BlockItem) stack.getItem()).getBlock().getDefaultState(), null, null, tintIndex),
                ModBlocks.tallGrass);

        registerProperty(ModItems.sling, new ResourceLocation("pull"), (stack, w, ent) -> {
            if(ent == null) {
                return 0.0F;
            } else {
                return ent.getActiveItemStack() != stack ? 0.0f
                        : (float) (stack.getUseDuration() - ent.getItemInUseCount()) / 20.0f;
            }
        });
        registerProperty(ModItems.sling, new ResourceLocation("pulling"), (ent, w, stack) -> {
            return stack != null && stack.isHandActive() && stack.getActiveItemStack() == ent ? 1.0F
                    : 0.0F;
        });
    }

    @SubscribeEvent
    @SuppressWarnings("")
    public void onClientTick(TickEvent.ClientTickEvent e) {
        if(e.phase != TickEvent.Phase.END) {
            return;
        }
        StatusDisplayGui.INSTANCE.tick();
        animateTick(ModBlocks.barrierLight);
        animateTick(ModBlocks.barrierSolid);
    }

    @SuppressWarnings("")
    private void animateTick(Block b) {
        Minecraft mc = Minecraft.getInstance();
        if(mc.isGamePaused() || mc.world == null) {
            return;
        }
        int posX = MathHelper.floor(mc.player.getPosX());
        int posY = MathHelper.floor(mc.player.getPosY());
        int posZ = MathHelper.floor(mc.player.getPosZ());

        boolean flag = false;
        if(mc.playerController.getCurrentGameType() == GameType.CREATIVE) {
            for(ItemStack itemstack : mc.player.getHeldEquipment()) {
                if(itemstack.getItem() == b.asItem()) {
                    flag = true;
                    break;
                }
            }
        }
        if(!flag) {
            return;
        }

        BlockPos.Mutable pos = new BlockPos.Mutable();
        for(int j = 0; j < 667; ++j) {
            animateTick(mc.world, b, posX, posY, posZ, 16, pos);
            animateTick(mc.world, b, posX, posY, posZ, 32, pos);
        }
    }

    private void animateTick(ClientWorld w, Block b, int x, int y, int z, int offset,
            BlockPos.Mutable pos) {
        x += w.rand.nextInt(offset) - w.rand.nextInt(offset);
        y += w.rand.nextInt(offset) - w.rand.nextInt(offset);
        z += w.rand.nextInt(offset) - w.rand.nextInt(offset);
        pos.setPos(x, y, z);
        BlockState blockstate = w.getBlockState(pos);
        if(blockstate.getBlock() == b) {
            w.addParticle(ParticleTypes.BARRIER, x + 0.5, y + 0.5, z + 0.5, 0.0, 0.0, 0.0);
        }
    }

    @SubscribeEvent
    public void onRenderNamePlate(RenderNameplateEvent e) {
        e.setResult(Event.Result.DENY);

        Entity ent = e.getEntity();
        EntityRendererManager erm = Minecraft.getInstance().getRenderManager();
        EntityRenderer<? super Entity> renderer = erm.getRenderer(ent);

        if(ClientReflectionUtils.canRenderName(renderer, ent)) {
            double d0 = erm.squareDistanceTo(ent);
            if(!(d0 > 4096.0D)) {
                boolean flag = !ent.isDiscrete();
                MatrixStack mStack = e.getMatrixStack();
                mStack.push();
                mStack.translate(0.0, ent.getHeight() + 0.5F, 0.0);
                mStack.rotate(erm.getCameraOrientation());
                mStack.scale(-0.025f, -0.025f, 0.025f);

                Matrix4f matrix4f = mStack.getLast().getMatrix();
                Minecraft mc = Minecraft.getInstance();
                float f1 = mc.gameSettings.getTextBackgroundOpacity(0.25F);
                int j = (int) (f1 * 255.0F) << 24;

                FontRenderer fontrenderer = erm.getFontRenderer();

                ITextComponent text = ent.getCustomName();
                if(text == null) {
                    text = ent.getDisplayName();
                }
                String s = text.getString();
                String[] parts = s.split("\n");

                int packedLight = renderer.getPackedLight(ent,
                        Minecraft.getInstance().getRenderPartialTicks());

                IRenderTypeBuffer buffer = e.getRenderTypeBuffer();

                Vector3f up = new Vector3f(0.0f, 9.0f * 1.15f * 0.025f, 0.0f);
                for(String line : parts) {
                    if(line.isEmpty()) {
                        matrix4f.translate(up);
                        continue;
                    }
                    float f2 = -0.5f * fontrenderer.getStringWidth(line);
                    fontrenderer.renderString(line, f2, 0.0f, 553648127, false, matrix4f, buffer,
                            flag, j, packedLight);
                    if(flag) {
                        fontrenderer.renderString(line, f2, 0.0f, -1, false, matrix4f, buffer,
                                false, 0, packedLight);
                    }
                    matrix4f.translate(up);
                }

                mStack.pop();
            }
        }
    }

    @SubscribeEvent
    public void onEmptyLeftClick(PlayerInteractEvent.LeftClickEmpty e) {
        ModPacketHandler.sendLeftClickEmpty();
    }

    @SubscribeEvent
    public void onRenderGui(RenderGameOverlayEvent.Pre e) {
        if(e.getType() == RenderGameOverlayEvent.ElementType.POTION_ICONS) {
            e.setCanceled(true);
        }
    }

    @SubscribeEvent
    public void onRenderGui(RenderGameOverlayEvent.Post e) {
        if(e.getType() == RenderGameOverlayEvent.ElementType.EXPERIENCE) {
            PlayerDisplayGui.INSTANCE.paint(e.getMatrixStack());
            StatusDisplayGui.INSTANCE.paint(e.getMatrixStack());
            PlayerHeadGui.INSTANCE.paint(e.getMatrixStack());
            ItemStackDisplayGui.INSTANCE.paint(e.getMatrixStack(), keyManager);
        }
    }

    @SubscribeEvent
    public void onRenderGui(GuiScreenEvent.InitGuiEvent e) {
        // workaround until a client side server leave event is back
        Screen gui = e.getGui();
        if(gui instanceof MainMenuScreen || gui instanceof MultiplayerScreen) {
            PlayerDisplayGui.INSTANCE.clear();
            StatusDisplayGui.INSTANCE.clear();
            PlayerHeadGui.INSTANCE.clear();
            ItemStackDisplayGui.INSTANCE.clear();
            ItemStackDisplayGui.INSTANCE.setActive(false);
        }
    }
}
