from PyQt5 import QtGui
import os
import pickle
from PyQt5.QtWidgets import QFileDialog,QMessageBox
from colorama import Fore, Back, Style, init


class ThemeManager:
    """
    the theme manager takes care of the theme
    """

    instance = None 

    def __init__(self,parent):
        self.theme = "bright" # current state

        self.parent = parent
        self.restore()
        self.christmas_mode = False 

        self.style_dark = {
            "main": self.read_file("styles/dark/main.txt")
            }

        self.style_bright ={
            "main": self.read_file("styles/bright/main.txt")
        }

        self.styles  = {
        "bright": self.style_bright,
        "dark": self.style_dark
        }

        self.__class__.instance = self 

    def activate_christmas_mode(self):
        print("*** CHRISTMAS MODE ***")
        self.christmas_mode = True 

        self.style_bright ={
            "main": self.read_file("styles/christmas/main.txt")
        }

        self.styles  = {
        "bright": self.style_bright,
        "dark": self.style_dark
        }

        self.parent.switch_theme()
        self.parent.switch_theme()
    
    def restore(self):
        # default values
        self.dark_theme = [#QtGui.QColor(50, 50, 50 , 255),
                           QtGui.QColor(130, 130, 130 , 255),
                           QtGui.QColor(120, 120, 120, 255),
                           QtGui.QColor(220,220,220, 120), # transaction lines
                            QtGui.QColor(177,177,177 , 255),
                            QtGui.QColor(85, 170, 255,255), # QtGui.QColor(175,175,175, 255), # avtive connection
                            QtGui.QColor(180, 180, 180, 255),
                            QtGui.QColor(250,250,250,255), # QtGui.QColor(72,72,72 , 255), # box labels
                            QtGui.QColor(120,120,120,80) # background
                           ]

        self.bright_theme =[QtGui.QColor(50, 50, 50 , 255),
                           QtGui.QColor(20, 20, 20, 255),
                           QtGui.QColor(81, 81, 81 , 80), # transaction lines
                            QtGui.QColor(221,221,221, 200),
                           QtGui.QColor(255,96,99,255), # QtGui.QColor(230, 230, 230, 255), # active connection
                            QtGui.QColor(210, 210, 210, 255),
                            QtGui.QColor(47, 47,47 , 255), # box labels
                            QtGui.QColor(80,80,80,100) # background
                           ]

        self.colors = {
            "dark": self.dark_theme,
            "bright": self.bright_theme
        }
        # self.restore_buttons()
        self.parent.update()

    def print_theme(self, theme):
        # print a theme in console 

        def rgb_to_ansi(r, g, b):
                return f"\033[48;2;{r};{g};{b}m"
        for color in theme:
            r, g, b, _ = color.getRgb()  # Extract RGB values
            ansi_code = rgb_to_ansi(r, g, b)  # Get the ANSI code for the color
            reset_code = "\033[0m"  # Reset code to clear formatting
            print(f"{ansi_code}  RGB: {r}, {g}, {b}  {reset_code}")


    def load_colors(self, filename=None, dirname=None):

        # self.restore()

        if filename is None:
            filename = QFileDialog.getOpenFileName(self.parent, 'Open file',os.getcwd(), "Attune Theme Files (*.sfctheme)")[0]
        print("load colors -> filename", filename)

        if filename is not None and filename != "":

            success = False
            try:
                with open(filename,"rb") as file:
                    theme = pickle.load(file)
                    self.print_theme(theme)    
                    self.colors[self.theme] = theme
                    #self.restore_buttons()
                success = True
            except Exception as e:
                pass # self.parent.notify("1) Exception in load_colors: %s" % str(e), title="Exception")

            if not success:
                
                try:
                    filename = os.path.split(filename)[1]
                    foldername = os.path.dirname(self.parent.current_file)
                    filename = os.path.join(foldername,filename)
                
                    with open(filename,"rb") as file:
                        theme = pickle.load(file)
                        self.colors[self.theme] = theme
                    #self.restore_buttons()
                    success = True
                except:
                    filename = os.path.split(filename)[1]
                    foldername = dirname # os.path.dirname(self.parent.current_file)
                    filename = os.path.join(foldername,filename)
                
                    with open(filename,"rb") as file:
                        theme = pickle.load(file)
                        self.colors[self.theme] = theme
                    #self.restore_buttons()
                    success = True
                    
            # self.parent.notify("2) Exception in load_colors: %s" % str(e), title="Exception")

            if not success:
                self.parent.statusBar().showMessage("fopen theme from %s" % filename) #  , title="Error")

    def save_colors(self,filename=None):
        # save the colortheme to reative path

        if filename is None:
            try:
                filename = self.parent.current_file
                ftheme = filename[:-5]+"sfctheme" # absolute file path
                folder,ftheme = os.path.split(ftheme) # convert to relative file path
                filename = ftheme 
            except Exception as e:
                print("Exception: %s" % str(e))

        try:
            # get the path of the main file
            foldername = os.path.dirname(self.parent.current_file)

            # join path to save under same folder as main file
            filename = os.path.join(foldername,filename)

            print("saving theme...")
            ssheets = []
            for i,color in enumerate(self.colors[self.theme]):
                clr = color # btn_table[i+1] # .palette().button().color()
                clr.setAlpha(color.alpha())
                ssheets.append(clr)
                print(clr.alpha())

            # (ssheets)
            # theme = self.colors[self.theme]
            self.print_theme(ssheets)

            if filename is None:
                filename = QFileDialog.getSaveFileName(self.parent, 'Save file',os.getcwd(), "Attune Theme Files (*.sfctheme)")[0]

            if filename is not None and filename != "":
                print("write ",filename)
                with open(filename,"wb") as file:
                    pickle.dump(ssheets,file)

        except Exception as e:
            self.parent.notify("An error occurred: Could not save colors.\n %s" % str(e),title="Error")

    def get_color(self,category):
        """
        get the color given the current theme
        :param category: int, which layer of the color theme you want
        """
        return self.colors[self.theme][category]
    
    def get_stylesheet(self,category):
        return self.styles[self.theme][category]


    def get_notification_style(self):
        # style of notifiaction window

        notification_styles = {
            "dark": "QLabel{color:white; font-size:12pt;}",
            "bright": "QLabel{color:black; font-size:12pt;}"
        }
        
        return notification_styles[self.theme]

    def get_table_style(self):

        dark_table_style = self.read_file("styles/dark/tables.txt")
        bright_table_style = self.read_file("styles/bright/tables.txt")

        if self.christmas_mode:
            bright_table_style = self.read_file("styles/christmas/tables.txt")

        table_styles = {
            "dark": dark_table_style,
            "bright": bright_table_style
        }

        return table_styles[self.theme]


    def get_background_style(self):
        # background color for dialogs

        dark_bg_style=self.read_file("styles/dark/background.txt")
        bright_bg_style=self.read_file("styles/bright/background.txt")

        if self.christmas_mode:
            bright_table_style = self.read_file("styles/christmas/background.txt")

        notification_styles = {
            "dark": dark_bg_style,
            "bright": bright_bg_style
        }

        return notification_styles[self.theme]
    
    def read_file(self,fname):

        # fname = "./attune/src/styles/" + fname
        home = os.path.dirname(os.path.abspath(__file__))
        fname = os.path.join(home, fname)

        with open(fname,"r") as file:
            return str(file.read())
