using Dalamud.Interface.Internal;
using Dalamud.Interface.Textures;
using Dalamud.Interface.Textures.TextureWraps;
using Lumina.Excel;
using static Dalamud.Plugin.Services.ITextureProvider;

namespace HSUI.Helpers
{
    public class TexturesHelper
    {
        public static IDalamudTextureWrap? GetTexture<T>(uint rowId, uint stackCount = 0, bool hdIcon = true) where T : struct, IExcelRow<T>
        {
            ExcelSheet<T> sheet = Plugin.DataManager.GetExcelSheet<T>();
            return sheet == null ? null : GetTexture<T>(sheet.GetRow(rowId), stackCount, hdIcon);
        }

        public static IDalamudTextureWrap? GetTexture<T>(dynamic row, uint stackCount = 0, bool hdIcon = true) where T : struct, IExcelRow<T>
        {
            dynamic iconId = row.Icon;
            return GetTextureFromIconId(iconId, stackCount, hdIcon);
        }

        public static IDalamudTextureWrap? GetTextureFromIconId(uint iconId, uint stackCount = 0, bool hdIcon = true)
        {
            if (iconId == 0)
                return null;

            try
            {
                // Game encodes item icons: iconId >= 1000000 means HQ; actual icon = iconId % 1000000
                uint actualIconId = iconId >= 1000000 ? (iconId % 1000000) + stackCount : iconId + stackCount;
                bool itemHq = iconId >= 1000000;
                GameIconLookup lookup = new GameIconLookup(actualIconId, itemHq, hdIcon);
                return Plugin.TextureProvider.GetFromGameIcon(lookup).GetWrapOrDefault();
            }
            catch
            {
                // GetFromGameIcon can throw for invalid/unsupported icon IDs (e.g. certain inventory item icons during drag-drop)
                return null;
            }
        }

        public static IDalamudTextureWrap? GetTextureFromPath(string path)
        {
            return Plugin.TextureProvider.GetFromGame(path).GetWrapOrDefault();
        }
    }
}
