"""
VN Scene Script Ext - vntext10
Provide functions to call VNText functions to change vntext in scene

f_dyntext,

v1.0: 
- add f_dyntext function

v1.1:
- add f_setvntext, f_vntextvisible, f_vntextcolor, f_vntextsyncvnss, , f_vntextunsync

v1.2:
- bug fix for f_vntextsyncbrvar
- format update


Function: f_dyntext - update dynamic texts
Syntax:
    :a:n:f_dyntext:::textinfo
    where 'textinfo': dynamic text info export from VNTextManager

Function: f_setvntext - update text of a vntext by id, can use brVar to format text
Syntax:
    f_setvntext:id:varlist:text

Function: f_vntextvisible - show/hide a vntext by id
Syntax:
    f_vntextvisible:id:visible

Function: f_vntextcolor - set vntext color by id, color in RRGGBB or RRGGBBAA format
Syntax:
    f_vntextcolor:id:color

Function: f_vntextsyncvnss - setup vntext (by id) sync with vnss dialog text
Syntax:
    f_vntextsyncvnss:id:who:option
    where option can be: autohide, titleonly, addtitle, usetitlecolor

Function: f_vntextsyncbrvar - setup vntext (by id) sync with blackrain variable
Syntax:
    f_vntextsyncbrvar:id:vari_list:text_format
    where vari_list is the list of blackrain variable split by comma, like "a,b"
          text_format is how to format variable into texts, refer to str.format() function

Function: f_vntextsyncvar - setup vntext (by id) sync with any variable, advanced user only!
Syntax:
    f_vntextsyncvar:id:vari:text_format
    where vari_path is the list of variable path from game object, like "game.engine_name"
          text_format is how to format variable into texts, refer to str.format() function
    This is mainly designed to monitor variable in relatime when developping VNGE function.
    For example, create a vntxt1 in scene and set:
        f_vntextsyncvar:vntxt1:game.timers[0],game.scenedata.actors["act0"].get_anime_normalizedtime():game timer0:{}\nAct0 Anime timer:{}
    Then vntxt1 will display the value in setted format and update realtime, like:
        game timer0:0.122
        Act0 Anime timer:0.565

Function: f_vntextunsync - remove vntext (by id) sync setting
Syntax:
    f_vntextunsync:id

"""
from UnityEngine import Color

def custom_action(game,act):
    """:type game: vngameengine.VNNeoController"""
    from vntext import get_vntext_manager
    mgr = get_vntext_manager(game)

    if act["action"] == "f_dyntext":
        try:
            textinfo = act["actionparam3"]
            mgr.importDynamicTextSetting(textinfo)
        except Exception as e:
            print("vntext error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_setvntext":
        try:
            tid = act["actionparam"]
            varlist = act["actionparam2"]
            text = act["actionparam3"].replace("\\n","\n")
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # format by varlist
            if len(varlist) > 0:
                valuelist = []
                if hasattr(game.gdata, 'brVars'):
                    for var in varlist.split(','):
                        if var in game.gdata.brVars:
                            valuelist.append(game.gdata.brVars[var])
                        else:
                            raise Exception("%s in varlist is not existed!"%var)
                else:
                    raise Exception("No blackrain var setted yet!")
                text = text.format(*valuelist)
            # set text
            vi.setText(text)
            vi.animePlay()
        except Exception as e:
            print("f_setvntext error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextvisible":
        try:
            tid = act["actionparam"]
            visible = bool(eval(act["actionparam2"]))
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # set visible
            vi.setVisible(visible)
        except Exception as e:
            print("f_vntextvisible error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextcolor":
        try:
            tid = act["actionparam"]
            tcolor = act["actionparam2"]
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # check color
            try:
                if len(tcolor) == 6:
                    r = int(tcolor[0:2], 16)
                    g = int(tcolor[2:4], 16)
                    b = int(tcolor[4:6], 16)
                    color = Color(float(r) / 255.0, float(g) / 255.0, float(b) / 255.0)
                elif len(tcolor) == 8:
                    r = int(tcolor[0:2], 16)
                    g = int(tcolor[2:4], 16)
                    b = int(tcolor[4:6], 16)
                    a = int(tcolor[6:8], 16)
                    color = Color(float(r) / 255.0, float(g) / 255.0, float(b) / 255.0, float(a) / 255.0)
                else:
                    raise Exception()
            except:
                raise Exception("Color code %s is not in valid format"%tcolor)
            # set visible
            vi.setColor(color)
        except Exception as e:
            print("f_vntextcolor error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextsyncvnss":
        try:
            tid = act["actionparam"]
            who = act["actionparam2"]
            option = act["actionparam3"].lower().split(",")
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # check opt
            opt = {}
            opt["titleonly"] = "titleonly" in option
            opt["addtitle"] = "addtitle" in option
            opt["usetitlecolor"] = "usetitlecolor" in option
            opt["autohide"] = "autohide" in option
            # register sync
            mgr.setTextSync(tid, "vnss", (who, opt))
        except Exception as e:
            print("f_vntextsyncvnss error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextsyncbrvar":
        try:
            tid = act["actionparam"]
            variList = act["actionparam2"]
            textFmt = act["actionparam3"]
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # build variPaths
            variPaths = []
            if len(variList) > 0:
                for var in variList.split(","):
                    variPath = "game.gdata.brVars['%s']"%var
                    variPaths.append(variPath)
            # register sync
            mgr.setTextSync(tid, "vari", (textFmt, variPaths))
        except Exception as e:
            print("f_vntextsyncbrvar error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextsyncvar":
        try:
            tid = act["actionparam"]
            paths = act["actionparam2"]
            textFmt = act["actionparam3"]
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # build variPaths
            if len(paths) > 0:
                #variPaths = eval(paths)
                variPaths = paths.split(",")
            else:
                variPaths = []
            # register sync
            mgr.setTextSync(tid, "vari", (textFmt, variPaths))
        except Exception as e:
            print("f_vntextsyncvar error, can't parse command '%s':"%act["origintext"], e)
        return True

    if act["action"] == "f_vntextunsync":
        try:
            tid = act["actionparam"]
            # check id
            vi = mgr.getTextInfo(tid)
            if vi == None:
                raise Exception("VNText info not found for id = %s"%tid)
            # remove sync
            mgr.removeTextSync(tid)
        except Exception as e:
            print("f_vntextunsync error, can't parse command '%s':"%act["origintext"], e)
        return True

def debug_buttons(game,state):
    return [] # if we want no additional buttons

    # return in format of set_buttons_alt
    #return ["Demo btn (keitaro10)", demo1]