import darkdetect
from PyQt6 import QtGui
import re
from src import settings


config = settings.icons

path = config.path


class Icon:
    def __init__(self, icon_type, widget=None, recolor=True, color=None):
        """Set an icon to a widget or window. Recolors the icon if needed

        Args:
            icon_type (str): Name of the icon in the config file
            widget (Any, optional): Object the icon will be added to. Defaults to None.
            recolor (bool, optional): If Icon should be recolored. Defaults to True.
            color (str, optional): Color type to use. Configured in config file. Defaults to None.
        """
        assert icon_type in settings.icons.icons.keys(), (
            f"Icon {icon_type} not in config file"
        )
        assert color in settings.icons.colors.keys() or color is None, (
            f"Color {color} not in config file"
        )
        icon = settings.icons.get(icon_type)
        dark = darkdetect.isDark()
        if dark:
            self.color = config.colors.dark
        else:
            self.color = config.colors.light
        if color:
            self.color = config.colors[color]
        self.icon = QtGui.QIcon()
        self.icon_path = path + icon
        recolor = (
            False
            if icon_type.endswith(".ico") or icon_type.endswith(".png")
            else recolor
        )
        self.add_icon(self.icon_path, recolor)
        if widget is not None:
            try:
                widget.setIcon(self.icon)
            except AttributeError:
                widget.setWindowIcon(self.icon)

    def add_icon(self, icon_path, recolor=False):
        icon = self.changeColor(icon_path, recolor)

        # use icon bytes to create a pixmap
        pixmap = QtGui.QPixmap()
        pixmap.loadFromData(icon)

        self.icon.addPixmap(
            pixmap,
            QtGui.QIcon.Mode.Normal,
            QtGui.QIcon.State.Off,
        )

    def overwriteColor(self):
        # take the icon, read it as bytes and change the color in fill
        icon = self.changeColor(self.icon_path)
        cicon = str(icon)
        fill = re.search(r"fill=\"(.*?)\"", cicon).group(1)
        stroke = re.search(r"stroke=\"(.*?)\"", cicon)
        if stroke:
            stroke = stroke.group(1)

        if fill and stroke:
            # replace stroke
            newicon = icon.replace(stroke.encode(), config.color.encode())
        else:
            newicon = icon.replace(fill.encode(), config.color.encode())

        pixmap = QtGui.QPixmap()
        pixmap.loadFromData(newicon)

        self.icon.addPixmap(
            pixmap,
            QtGui.QIcon.Mode.Normal,
            QtGui.QIcon.State.Off,
        )
        return self.icon

    def changeColor(self, icon_path, recolor) -> bytes:
        """change the color of the svg icon to the color set in the config file

        Args:
            icon_path (str): the path to the icon, usually icons/[name].svg

        Returns:
            icon: a byte representation of the icon with the new color
        """
        color = self.color
        with open(icon_path, "rb") as file:
            icon = file.read()
        if recolor:
            cicon = str(icon)

            try:
                fill = re.search(r"fill=\"(.*?)\"", cicon).group(1)
            except AttributeError:
                fill = None
            if fill:
                icon = icon.replace(fill.encode(), color.encode())
        return icon


if __name__ == "__main__":
    print("This is a module and can not be executed directly.")
