
package de.winniepat.citrus.utils.texture;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.utils.SecurityUtils;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.*;
import net.minecraft.util.Identifier;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;

public class IconLoaderComponent {

    private static final String MOD_ID = "citrus";

    private static final Map<String, Identifier> CACHE = new ConcurrentHashMap<>();

    public static CompletableFuture<Identifier> getRankTexture(String uuid) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                URL rankUrl = new URI(Client.API_URL + "/rank/" + uuid).toURL();
                HttpURLConnection conn = (HttpURLConnection) rankUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("x-daily-key", SecurityUtils.getDailyKey());
                
                String rank;
                try (InputStream is = conn.getInputStream();
                     Scanner scanner = new Scanner(is)) {
                    rank = scanner.useDelimiter("\\A").next().trim().toLowerCase();
                }

                conn.disconnect();

                if (CACHE.containsKey(rank)) {
                    return CACHE.get(rank);
                }

                URL iconUrl = new URI(Client.CDN_URL + "/ranks/" + rank + ".png").toURL();
                try (InputStream is = iconUrl.openStream()) {
                    NativeImage image = NativeImage.read(is);
                    NativeImageBackedTexture texture = new NativeImageBackedTexture(image);

                    Identifier textureId = Identifier.of(MOD_ID, "ranks/" + rank);

                    MinecraftClient.getInstance().execute(() -> {
                        MinecraftClient.getInstance().getTextureManager().registerTexture(textureId, texture);
                    });

                    CACHE.put(rank, textureId);
                    return textureId;
                }
            } catch (Exception e) {
                Client.logger.error("Failed to get rank texture for UUID: {}", uuid, e);
                return null;
            }
        });
    }
}