package me.km;

import com.mojang.blaze3d.matrix.MatrixStack;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
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.Matrix4f;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.Vector3f;
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.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.LanguageMap;
import net.minecraft.world.GrassColors;
import net.minecraft.world.World;
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.event.entity.player.ItemTooltipEvent;
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();
        ClientReflectionUtils.updatePlayerRenderer();
    }

    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);
    }

    @SubscribeEvent
    public void onClientTick(TickEvent.ClientTickEvent e) {
        if(e.phase == TickEvent.Phase.END) {
            StatusDisplayGui.INSTANCE.tick();
        }
    }

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

        Entity ent = e.getEntity();
        EntityRendererManager erm = Minecraft.getInstance().getRenderManager();
        EntityRenderer 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();
                float f1 = Minecraft.getInstance().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.getFormattedText();
                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) {
                    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();
            StatusDisplayGui.INSTANCE.paint();
            PlayerHeadGui.INSTANCE.paint();
            ItemStackDisplayGui.INSTANCE.paint(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);
        }
    }

    @SubscribeEvent
    public void showingTooltip(ItemTooltipEvent e) {
        ItemStack stack = e.getItemStack();
        Item item = stack.getItem();
        if(item instanceof ArmorItem) {
            CompoundNBT com = stack.getTag();
            if(com != null && com.contains("magic")) {
                int magic = com.getInt("magic");
                if(magic != 0) {
                    List<ITextComponent> list = e.getToolTip();
                    for(int i = 0; i < list.size(); i++) {
                        if(list.get(i).getString().contains("+")) {
                            list.add(i, new StringTextComponent(
                                    String.format("%s+%d %s", TextFormatting.BLUE, magic,
                                            LanguageMap.getInstance().translateKey("magicarmor"))));
                            break;
                        }
                    }
                }
            }
        }
    }

    /*@SubscribeEvent
    public void test(net.minecraftforge.client.event.ClientChatEvent e)
    {
        net.minecraft.world.chunk.Chunk c = Minecraft.getInstance().player.world.getChunkAt(Minecraft.getInstance().player.getPosition());
        
        if(!e.getMessage().equals("run"))
        {
            return;
        }

        int cluster = 0;
        int blocks = 0;
        
        net.minecraft.util.math.BlockPos.MutableBlockPos pos = new net.minecraft.util.math.BlockPos.MutableBlockPos();

        for(int x = 0; x < 16; x += 4)
        {
            for(int z = 0; z < 16; z += 4)
            {
                for(int y = 0; y < 256; y += 16)
                {
                    cluster++;
                    pos.setPos(x, y, z);
                    blocks++;
                    net.minecraft.block.Block current = c.getBlockState(pos).getBlock();
                    for(int mx = 0; mx < 4; mx++)
                    {
                        for(int mz = 0; mz < 4; mz++)
                        {
                            for(int my = 0; my < 16; my++)
                            {
                                pos.setPos(x + mx, y + my, z + mz);
                                net.minecraft.block.Block next = c.getBlockState(pos).getBlock();
                                if(current != next)
                                {
                                    current = next;
                                    blocks++;
                                }
                            }
                        }
                    }
                }
            }
        }
        
        org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger();
        logger.info("------------------------------------");
        logger.info(String.format("cluster: %d", cluster));
        logger.info(String.format("blocks: %d", blocks));
        logger.info(String.format("compression rate: %f",  (16 * 16 * 256 * 16) / (cluster * 64.0 + blocks * 24.0)));
        
        cluster = 0;
        blocks = 0;

        for(int x = 0; x < 16; x++)
        {
            for(int z = 0; z < 16; z++)
            {
                cluster++;
                pos.setPos(x, 0, z);
                blocks++;
                net.minecraft.block.Block current = c.getBlockState(pos).getBlock();
                for(int y = 0; y < 256; y++)
                {
                    pos.setPos(x, y, z);
                    net.minecraft.block.Block next = c.getBlockState(pos).getBlock();
                    if(current != next)
                    {
                        current = next;
                        blocks++;
                    }
                }
            }
        }
        
        logger.info("------");
        logger.info(String.format("cluster %d blocks", cluster, blocks));
        logger.info(String.format("cluster: %d", cluster));
        logger.info(String.format("blocks: %d", blocks));
        logger.info(String.format("compression rate: %f",  (16 * 16 * 256 * 16) / (cluster * 64.0 + blocks * 24.0)));
        
        cluster = 1;
        blocks = 1;
        pos.setPos(0, 0, 0);
        net.minecraft.block.Block current = c.getBlockState(pos).getBlock();
        for(int y = 0; y < 256; y++)
        {
            for(int x = 0; x < 16; x++)
            {
                for(int z = 0; z < 16; z++)
                {
                    pos.setPos(x, y, z);
                    net.minecraft.block.Block next = c.getBlockState(pos).getBlock();
                    if(current != next)
                    {
                        current = next;
                        blocks++;
                    }
                }
            }
        }
        
        logger.info("------");
        logger.info(String.format("cluster %d blocks", cluster, blocks));
        logger.info(String.format("cluster: %d", cluster));
        logger.info(String.format("blocks: %d", blocks));
        logger.info(String.format("compression rate: %f",  (16 * 16 * 256 * 16) / (cluster * 64.0 + blocks * 24.0)));
    }*/
    
    /*@SubscribeEvent
    public void test(net.minecraftforge.client.event.ClientChatEvent e) {
        int size;
        try {
            size = Short.parseShort(e.getMessage());
        } catch(NumberFormatException ex) {
            return;
        }
        World w = Minecraft.getInstance().player.world;
        int idCounter = 0;
        HashMap<BlockState, Integer> mapping = new HashMap<>();
        int sizeY = Math.min(256, size);

        int index = 0;
        byte[] b = new byte[sizeY * size * size];

        BlockPos.Mutable pos = new BlockPos.Mutable();
        for(int x = 0; x < size; x++) {
            for(int y = 0; y < sizeY; y++) {
                for(int z = 0; z < size; z++) {
                    pos.setPos(x, y, z);
                    BlockState blockState = w.getBlockState(pos);
                    Integer id = mapping.get(blockState);
                    if(id == null) {
                        id = idCounter++;
                        mapping.put(blockState, id);
                    }
                    b[index++] = id.byteValue();
                }
            }
        }

        Thread th = new Thread(() -> {
            try(FileOutputStream out = new FileOutputStream(new File(String.format("%d_%d_data", size, size)))) {
                out.write(b);
            } catch(IOException ex) {
                ex.printStackTrace();
            }
        });
        th.start();

        org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger();
        logger.info("------------------------------------");
        logger.info(String.format("block types: %d", idCounter));
    }*/
    
    /*@SubscribeEvent
    public void test(net.minecraftforge.client.event.ClientChatEvent e) {
        int size;
        try {
            size = Integer.parseInt(e.getMessage());
        } catch(NumberFormatException ex) {
            return;
        }
        World w = Minecraft.getInstance().player.world;

        int[] counter = new int[256];

        int sizeY = Math.min(256, size);
        BlockPos.Mutable pos = new BlockPos.Mutable();
        for(int cx = 0; cx < size; cx += 16) {
            for(int cy = 0; cy < 16; cy += 16) {
                for(int cz = 0; cz < size; cz += 16) {
                    HashSet<BlockState> states = new HashSet<>();
                    for(int x = 0; x < 16; x++) {
                        for(int y = 0; y < 16; y++) {
                            for(int z = 0; z < 16; z++) {
                                pos.setPos(cx + x, cy + y, cz + z);
                                states.add(w.getBlockState(pos));
                            }
                        }
                    }
                    counter[states.size()]++;
                }
            }
        }

        org.apache.logging.log4j.Logger logger = org.apache.logging.log4j.LogManager.getLogger();
        logger.info("------------------------------------");
        for(int i = 0; i < counter.length; i++) {
            logger.info(String.format("%d: %d", i, counter[i]));
        }

    }*/
}
