#####################################
# @module    text_box.py            #
# @brief     simple UI Text box     #
# @author    Jamie Bird             #
# @date      Jan 2020               #
# @copyright Racelogic Ltd., 2020   #
#####################################

import gui
import ft8xx as ft
try:
    from gui_utils import Filter, Colours
except ImportError:
    raise ImportError ("This module requires the gui_utils function to work")

class UI_Box:
    ''' a 'widget' that can be ported into other applications.
        It displays either text (which can be formatted to screen width) or a parameter, encased in a box
        which can have a title and/or an optional parameter unit'''
    def __init__(self, x, y, h, w, title=None, target=None, font=33, title_font=23, unit_font=23, val=0, bg_colour=gui.RGB(0,0,0),
                 line_colour=gui.RGB(100,100,100), filter=False, unit='', text_height=0.23):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.bg_colour = bg_colour
        self.title = [title]
        self.line_colour = line_colour
        self.val = [str(val)] #line_1
        self.line_val_h = [int(self.y + (self.h * text_height))]
        self.line_2_h = [-100]
        self.line_2 = [''] # only used in multiline messages
        self.unit = [unit]
        self.font = font
        self.title_font = title_font
        self.unit_font = unit_font
        self.filter = Filter() if filter else lambda unfiltered: unfiltered
        # self.title_font = title_font
        self.line_width = 3
        self.gui_l_index = None
        self.gui_col_index = None
        self.target = target
        self.target_col = gui.DL_COLOR(Colours.green)

        self.set_defaults()

    def set_title(self, title):
        self.title[0] = title

    def draw(self):
        '''returns the box GUI list to add to the screen draw function'''
        self.gui_l = [
                gui.SUBLIST,
                [gui.DL_COLOR(self.line_colour)],
                [gui.DL_LINE_WIDTH(10)],
                [gui.DL_COLOR_A(150)],
                [gui.DL_BEGIN(gui.PRIM_RECTS)],
                [gui.DL_VERTEX2F(self.x, self.y)], # Outer box
                [gui.DL_VERTEX2F(self.x + self.w, self.y + self.h)],
                [gui.DL_COLOR(self.bg_colour)],
                [gui.DL_COLOR_A(200)],
                [gui.DL_VERTEX2F(self.x + self.line_width, self.y + self.line_width)], # Inner box
                [gui.DL_VERTEX2F(self.x + (self.w-self.line_width), self.y + (self.h-self.line_width))],
                [gui.DL_END()],
                [gui.DL_COLOR(self.line_colour)],
                # [gui.CTRL_TEXT, 100, 400, 24, 0, 'Test 2'],
                [gui.DL_COLOR_A(255)],
                [gui.CTRL_TEXT, int(self.x + (self.w *0.5)), int(self.y), 23, gui.OPT_CENTERX, self.title],
                [gui.CTRL_TEXT, int(self.x + (self.w *0.85)), int(self.y + (self.h *0.8)), 23, gui.OPT_CENTERX, self.unit],
                [gui.DL_COLOR(Colours.white)],
                [gui.CTRL_TEXT, int(self.x + (self.w *0.5)), self.line_val_h, self.font, gui.OPT_CENTERX, self.val],
                [gui.CTRL_TEXT, int(self.x + (self.w *0.5)), self.line_2_h, self.font, gui.OPT_CENTERX, self.line_2],
            ]
        self.gui_col_index = len(self.gui_l)-3
        # print(self.gui_l)
        return self.gui_l

    def update_vals(self, value):
        '''only use if updating a numerical parameter'''
        if (-0.1 < value < 0.1): #Catches weird '-0.0' displayed error
            self.val[0] = "{:.1f}".format(0)
        else:
            self.val[0] = "{:.1f}".format(self.filter(value))
        # self.check_limit()

    def update_unit(self, unit):
        self.unit[0] = unit

    def set_text(self, string, string_2=None, line_1_h=0.2, line_2_h=0.6):
        '''use if updating a message or text string'''
        self.val[0] = string
        if string_2:
            self.line_2[0] = string_2
            self.line_val_h[0] = int(self.y + (self.h * line_1_h))
            self.line_2_h[0] = int(self.y + (self.h * line_2_h))
        else:
            self.line_2[0] = ''
            self.line_val_h[0] = self.defaults['line_val_h'][0]
            self.line_2_h[0] = -100

        #TODO; Get Multi-line working Properly
        #TODO: from gui_utils import FT_font_manager(), use text() method
        # if (string.rstrip('\"') != string) and (string.count('\"') == 2):
        #     swap = True
        # else:
        #     swap = False
        # string = string.strip('\"')
        # user_str = string.split('\"')
        # if swap:
        #     user_str.insert(0, user_str.pop())
        # # user_str = string.split('|')
        # if len(user_str) > 1:
        #     # print("USER STRING")
        #     lines = []
        #     for block in user_str:
        #         lines.append(format_multi_line(block, 1, self.w, 5)[0])
        # else:
        #     # print("AUTO STRING")
        #     lines = format_multi_line(string, 2, self.w, 5)
        # if len(lines) > 2:
        #     self.val[0] = "Error: Max Lines Exceeded"
        #     # sort this out
        # else:
        #     self.val[0] = lines[0]
        #     if len(lines) == 2:
        #         self.line_2[0] = lines[1]
        #         self.line_val_h[0] = int(self.y + (self.h * 0.2))
        #         self.line_2_h[0] = int(self.y + (self.h * 0.6))
        #     else:
        #         self.line_2[0] = ''
        #         self.line_val_h[0] = self.defaults['line_val_h'][0] #int(self.y + (self.h * 0.4))
        #         self.line_2_h[0] = -100

    def set_limit(self, limit):
        self.target = limit

    def set_main_gui_index(self, index):
        self.gui_l_index = index

    def check_limit(self):
        if self.target:
            if float(self.val[0]) > (self.target):
                self.set_colour(self.target_col)
            else:
                self.set_colour(gui.DL_COLOR(Colours.white))
        #TODO: Get Target to work in both directiona
            # if float(self.val[0]) < (self.target):
            #     self.set_colour(self.target_col)
            # else:
            #     self.set_colour(gui.DL_COLOR(Colours.white))

    def set_colour(self, colour):
        '''set text colour'''
        self.gui_l[self.gui_col_index][0] = colour
        #INFO If this doesn't work, make the main gui list global,
        #INFO set the gui_index for the box with 'set_main_gui_index()'
        #INFO then use the following
        # global gui_l
        # gui_l[self.gui_l_index][self.gui_col_index][0] = colour

    def set_defaults(self):
        '''save default values incase we want to reconstruct the box'''
        self.defaults = self.__dict__.copy()
        for key, val in self.defaults.items():
            if isinstance(val, list):
                self.defaults[key] = tuple(val) # stops values changing from linked list
