import os
import bpy
import bpy.utils.previews

# We can store multiple preview collections here,
# however in this example we only store "main"
preview_collections = {}

def getPreviewIcon(name: str) -> int or None:
    register()
    col = preview_collections["main"]
    if name in col:
        entry = col[name]
        if entry is not None:
            return entry.icon_id
    return None

def registerIcon(name: str, path: str):
    register()
    # check if path is relative
    if not os.path.isabs(path):
        path = os.path.join(icons_dir, path)
    # test if it exists
    if not os.path.exists(path):
        print("Icon not found", path)
        return
    res = preview_collections["main"].load(name, path, 'IMAGE')
    print("Registered icon", name, path, res)


icons_dir = os.path.join(os.path.dirname(__file__), "icons")
registered = False

# https://docs.blender.org/api/2.82a/bpy.utils.previews.html
def register():
    global registered
    if registered:
        return
    registered = True

    pcoll = bpy.utils.previews.new()
    preview_collections["main"] = pcoll
    registerIcon("logo", "logo.png")
    registerIcon("logo_small", "logo_small.png")
    registerIcon("logo_small_bw", "logo_small_bw.png")
    registerIcon("update", "update.png")
    registerIcon("glitch", "glitch.png")
    print("Registered Needle icons...")


def unregister():
    global registered
    registered = False
    for pcoll in preview_collections.values():
        bpy.utils.previews.remove(pcoll)
    preview_collections.clear()