package de.winniepat.citrus.utils.texture;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.utils.SecurityUtils;
import io.wispforest.owo.ui.base.BaseComponent;
import io.wispforest.owo.ui.core.*;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.texture.*;
import net.minecraft.util.*;

import java.io.InputStream;
import java.net.URI;
import java.net.http.*;
import java.util.concurrent.CompletableFuture;

public class ModIconComponent extends BaseComponent {

    private static final String ICON_URL = Client.API_URL + "/client/logo.png";
    public static Identifier LOADED_TEXTURE = null;
    private static boolean loadingStarted = false;

    public ModIconComponent() {
        this.sizing(Sizing.fixed(20), Sizing.fixed(20));
        startLoading();
    }

    private static void startLoading() {
        if (loadingStarted || LOADED_TEXTURE != null) return;
        loadingStarted = true;

        CompletableFuture.runAsync(() -> {
            try {
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(ICON_URL))
                        .header("x-daily-key", SecurityUtils.getDailyKey())
                        .GET()
                        .build();

                HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

                if (response.statusCode() == 200) {
                    try (InputStream is = response.body()) {
                        NativeImage image = NativeImage.read(is);
                        NativeImageBackedTexture texture = new NativeImageBackedTexture(image);

                        MinecraftClient.getInstance().execute(() -> {
                            LOADED_TEXTURE = MinecraftClient.getInstance()
                                    .getTextureManager()
                                    .registerDynamicTexture("citrus_logo", texture);
                        });
                    }
                }
            } catch (Exception e) {
                Client.logger.error("Failed to load icon from CDN", e);
                loadingStarted = false;
            }
        }, Util.getMainWorkerExecutor());
    }

    @Override
    public void draw(OwoUIDrawContext context, int mouseX, int mouseY, float partialTick, float delta) {
        if (LOADED_TEXTURE == null) {
            return;
        }

        context.drawTexture(
                LOADED_TEXTURE,
                x(), y(),
                20, 20,
                0, 0,
                20, 20,
                20, 20
        );
    }
}