package top.leisuretimedock.dglabgame.util;

import com.lowdragmc.lowdraglib.LDLib;
import com.lowdragmc.lowdraglib.gui.editor.data.UIProject;
import com.lowdragmc.lowdraglib.gui.widget.WidgetGroup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraftforge.fml.loading.FMLEnvironment;
import org.jetbrains.annotations.NotNull;
import top.leisuretimedock.dglabgame.DGLabGame;

import javax.annotation.Nullable;
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.Optional;
import java.util.function.Supplier;

public class UILoader {
    /**
     * 从模组的 assets 目录加载 UI 文件
     * @param location UI 文件的资源路径，例如 new ResourceLocation("dglabgame", "ui/agreement.ui")
     * @return UI 文件的 Supplier，失败返回 null
     */
    @Nullable
    public static Supplier<WidgetGroup> loadUIFromAssets(ResourceLocation location) {
        try {
            ResourceManager resourceManager = getResourceManager();
            if (resourceManager == null) {
                LDLib.LOGGER.error("Resource manager not available");
                return null;
            }

            // 尝试不同的文件扩展名
            String[] extensions = {".ui", ".ui.nbt", ".nbt"};
            CompoundTag tag = null;

            for (String ext : extensions) {
                String path = location.getPath();
                if (!path.endsWith(ext)) {
                    path = path + ext;
                }
                ResourceLocation fullLocation = new ResourceLocation(location.getNamespace(), path);

                Optional<Resource> resource = resourceManager.getResource(fullLocation);
                if (resource.isPresent()) {
                    try (InputStream inputStream = resource.get().open()) {
                        // 先尝试未压缩的格式
                        try {
                            DataInputStream dataInput = new DataInputStream(inputStream);
                            tag = NbtIo.read(dataInput);
                            LDLib.LOGGER.info("Successfully loaded uncompressed NBT from: {}", fullLocation);
                            break;
                        } catch (Exception e) {
                            // 如果失败，尝试压缩格式
                            try {
                                // 需要重新获取 inputStream
                                try (InputStream newStream = resource.get().open()) {
                                    tag = NbtIo.readCompressed(newStream);
                                    LDLib.LOGGER.info("Successfully loaded compressed NBT from: {}", fullLocation);
                                    break;
                                }
                            } catch (Exception ex) {
                                // 继续尝试下一个扩展名
                                LDLib.LOGGER.debug("Failed to load with extension {}: {}", ext, ex.getMessage());
                            }
                        }
                    }
                }
            }

            if (tag == null) {
                LDLib.LOGGER.error("Could not load UI file with any extension: {}", location);
                return null;
            }

            return UIProject.loadUIFromTag(tag);

        } catch (Exception e) {
            LDLib.LOGGER.error("Failed to load UI from assets: {}", location, e);
            return null;
        }
    }

    /**
     * 获取资源管理器（客户端专用）
     */
    @Nullable
    private static ResourceManager getResourceManager() {
        if (FMLEnvironment.dist.isClient()) {
            net.minecraft.client.Minecraft minecraft = net.minecraft.client.Minecraft.getInstance();
            return minecraft.getResourceManager();
        }
        return null;
    }

    @NotNull
    public static Optional<WidgetGroup> loadUI(String path) {
        try {
            Supplier<WidgetGroup> widgetGroupSupplier = loadUIFromAssets(DGLabGame.rl(path));
            if (widgetGroupSupplier != null) {
                return Optional.ofNullable(widgetGroupSupplier.get());
            }
        } catch (Exception e) {
            return Optional.empty();
        }
        return Optional.empty();
    }

    @NotNull
    public static Optional<WidgetGroup> loadUI(String modId,String path) {
        try {
            Supplier<WidgetGroup> widgetGroupSupplier = loadUIFromAssets(DGLabGame.rl(modId, path));
            if (widgetGroupSupplier != null) {
                return Optional.ofNullable(widgetGroupSupplier.get());
            }
        } catch (Exception e) {
            return Optional.empty();
        }
        return Optional.empty();
    }
    @NotNull
    public static Optional<WidgetGroup> loadUI(ResourceLocation location) {
        try {
            Supplier<WidgetGroup> widgetGroupSupplier = loadUIFromAssets(location);
            if (widgetGroupSupplier != null) {
                return Optional.ofNullable(widgetGroupSupplier.get());
            }
        } catch (Exception e) {
            return Optional.empty();
        }
        return Optional.empty();
    }
}
