import logging
import os
from PIL import Image
import OpenGL.GL as gl
from imgui_bundle import imgui


class IconLoader:
    def __init__(self, icons_dir=None):
        self._textures = {}
        if icons_dir is None:
            icons_dir = os.path.join(os.path.dirname(__file__), '..', 'assets', 'icons')
        self._icons_dir = icons_dir
        self._loaded = False

    def load(self):
        if self._loaded:
            return
        self._loaded = True
        if not os.path.isdir(self._icons_dir):
            return
        for fname in sorted(os.listdir(self._icons_dir)):
            if not fname.endswith('.png'):
                continue
            name = fname[:-4]
            path = os.path.join(self._icons_dir, fname)
            try:
                pil_img = Image.open(path).convert('RGBA')
                w, h = pil_img.size
                data = pil_img.tobytes()
                tex = gl.glGenTextures(1)
                gl.glBindTexture(gl.GL_TEXTURE_2D, tex)
                gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, w, h, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data)
                gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
                gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
                gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
                self._textures[name] = tex
            except Exception as e:
                logging.error(f"IconLoader: error loading {fname}: {e}")

    def has(self, name):
        return name in self._textures

    def get_tex(self, name):
        return self._textures.get(name)

    def button(self, name, fallback_label, tooltip=None, icon_size=22):
        tex = self._textures.get(name)
        if tex is not None:
            clicked = imgui.image_button(
                f"##{name}",
                imgui.ImTextureRef(tex),
                imgui.ImVec2(icon_size, icon_size)
            )
        else:
            btn_size = icon_size + 6
            clicked = imgui.button(fallback_label, imgui.ImVec2(btn_size, btn_size))
        return clicked
