# Copyright (C) 2022 Thomas Hoppe (h0bB1T). All rights reserved.
#
# Unauthorized copying of this file via any medium is strictly prohibited.
# Proprietary and confidential.

import os

from typing import Dict

from .previews_registry import PreviewsRegistry


class IconsRegistry:
    """
    Very simple interface to manage icons. Uses Previews from utils.
    Assumes icon file as 'data/icons/[name].png' and lazily loads on first access.
    """
    def __init__(self):
        PreviewsRegistry.instance().register('__icons')
        self.__icons = {} # type: Dict[str, int]


    def __path_colored(self, name: str, color: int) -> str:
        return os.path.join(os.path.dirname(__file__), '..', 'data', 'icons', 'colored', f'{name.lower()}-{hex(color)}.png')
    
    def __colored_icon_exists(self, name: str, color: str) -> bool:
        exists = os.path.exists(self.__path_colored(name, color))
        if not exists:
            print(f'("{name}", {hex(color)}),')
        return exists
    
    def __get_colored_icon(self, name: str, color: int) -> int:
        fixed_name = f'{name.lower()}-{hex(color)}'
        if fixed_name not in self.__icons:
            self.__icons[fixed_name] = PreviewsRegistry.instance().collection('__icons').load(fixed_name, self.__path_colored(name, color))
        return self.__icons[fixed_name]

    def colored_icon_exists(name: str, color: int) -> bool:
        return IconsRegistry.instance().__colored_icon_exists(name, color)
    
    def get_colored_icon(name: str, color: int) -> int:
        return IconsRegistry.instance().__get_colored_icon(name, color)
    

    def __path(self, name: str) -> str:
        return os.path.join(os.path.dirname(__file__), '..', 'data', 'icons', f'{name}.png')

    def __icon_exists(self, name: str) -> bool:
        return os.path.exists(self.__path(name))
    
    def __get_icon(self, name: str) -> int:
        if name not in self.__icons:
            self.__icons[name] = PreviewsRegistry.instance().collection('__icons').load(name, self.__path(name))
        return self.__icons[name]

    def icon_exists(name: str) -> bool:
        return IconsRegistry.instance().__icon_exists(name)
    
    def get_icon(name: str) -> int:
        return IconsRegistry.instance().__get_icon(name)


    @staticmethod
    def instance() -> 'IconsRegistry':
        """
        Access as singleton.
        """
        global _instance
        return _instance


_instance = IconsRegistry()
