package me.km.overrides;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.UUID;
import java.util.function.Consumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.apache.logging.log4j.LogManager;

@OnlyIn(Dist.CLIENT)
public class PlayerCapeLoader {
    private static class Data {
        private ResourceLocation cape;
    }

    public final static PlayerCapeLoader INSTANCE = new PlayerCapeLoader();

    private final HashMap<UUID, Data> skins = new HashMap<>();

    private final TextureManager manager = Minecraft.getInstance().getRenderManager().textureManager;

    private PlayerCapeLoader() {
    }

    public ResourceLocation getTexture(UUID uuid) {
        Data oldData = skins.get(uuid);
        if(oldData != null) {
            return oldData.cape;
        }
        Data newData = new Data();
        skins.put(uuid, newData);
        downloadCape(uuid, image -> {
            newData.cape = manager.getDynamicTextureLocation("cape_" + uuid, new DynamicTexture(image));
        });
        return null;
    }

    private void downloadCape(UUID uuid, Consumer<NativeImage> delayed) {
        new Thread(() -> {
            HttpURLConnection httpurlconnection = null;
            try {
                httpurlconnection = (HttpURLConnection) (new URL(String.format("http://skins.hammerle.me/cape_%s.png", uuid)))
                        .openConnection(Minecraft.getInstance().getProxy());
                httpurlconnection.setDoInput(true);
                httpurlconnection.setDoOutput(false);
                httpurlconnection.connect();

                int code = httpurlconnection.getResponseCode();
                if(code != 200) {
                    return;
                }

                NativeImage image = NativeImage.read(httpurlconnection.getInputStream());
                Minecraft.getInstance().enqueue(() -> delayed.accept(image));
            } catch(Exception ex) {
                LogManager.getLogger().warn("Error occurred when downloading skin, however, skin servers seem to be up.");
            } finally {
                if(httpurlconnection != null) {
                    httpurlconnection.disconnect();
                }
            }
        }).start();
    }
}
