# autorun for kernel stuff
# all PY files starting with "autorun_" will run an VNGE startup

vnge_pngvnss = ""

from vngameengine import tlbBtn_setColor, tlbBtn_VNGESSS
from UnityEngine import Color

def start_autorun(game):
    """:type game: vngameengine.VNNeoController"""

    if not game.isClassicStudio:
        if game.isSceneEventsSupported:
            game.event_reg_listener("scene_loaded_after",scene_loaded_after,"kernel",True)
            game.event_reg_listener("scene_loaded",scene_loaded,"kernel",True)
            game.event_reg_listener("scene_imported",scene_imported,"kernel",True)
            game.event_reg_listener("scene_imported_after",scene_imported_after,"kernel",True)

            game.event_reg_listener("scene_saved",scene_saved,"kernel",True)

    import scenesavestate
    scenesavestate.autorun_start(game)

    try:
        import vnphysics
        vnphysics.initialize(game)
    except:
        print("Fail to initialize vnphysics, module not installed?")

    try:
        import scenesavestatebuilder
        scenesavestatebuilder.initialize(game)
    except:
        print("Fail to initialize scenesavestatebuilder, module not installed?")

    #import vnanime
    fix_autotranslator(game)

def fix_autotranslator(game):
    """:type game: vngameengine.VNNeoController"""
    try:
        import clr
        clr.AddReference('XUnity.AutoTranslator.Plugin.Core')

        import clr
        clr.AddReference("System.Core")
        from System import Array

        from XUnity.AutoTranslator.Plugin.Core.Configuration import Settings
        old = [el for el in Settings.IgnoreTextStartingWith]
        old.extend([":","-"])
        ar = Array[str](old)
        Settings.IgnoreTextStartingWith = ar
        print(Settings.IgnoreTextStartingWith)
        game.logger_log_info("AutoTranslator fix applied. New IgnoreTextStartingWith "+str(Settings.IgnoreTextStartingWith))
    except Exception as e:
        game.logger_log_warning("Can't apply fix to AutoTranslator (you haven't it? not a big deal anyway): "+str(e),True)


def scene_saved(game, eventid, param):
    """:type game: vngameengine.VNNeoController"""
    #print("[KERNAL] save file: " + str(param))

    if(game.isSceneDataSaveSupported):
        # saving SSS data
        import scenesavestate
        if scenesavestate._sc != None:
            scenesavestate.scene_saved(game)

        import vnanime
        vnanime.scene_saved(game)

        import vnsound
        vnsound.scene_saved(game)

        global vnge_pngvnss
        game.dataPNG_save("vnge_vnss",vnge_pngvnss,"30.0")

        import vnactor
        vnactor.scene_saved(game)


def scene_loaded(game, eventid, param):
    """:type game: vngameengine.VNNeoController"""
    if(game.isSceneDataSaveSupported):
        import vnactor
        vnactor.scene_loaded(game)

        import scenesavestate
        if scenesavestate._sc != None:
            scenesavestate.scene_loaded(game)

        # loading vnge_png
        global vnge_pngvnss
        vnge_pngvnss = "" # clean at load

        data,version = game.dataPNG_load_checkversion("vnge_vnss",["30.0"])
        if data != None:
            if version == "30.0":
                vnge_pngvnss = data
            else:
                game.show_blocking_message_time("Can't load VNGE VNSS PNG data, unknown version=%s. Try upgrade to new VNGE"%version)

def scene_loaded_after(game, eventid, param):
    """:type game: vngameengine.VNNeoController"""
    # kernal work
    #print("[KERNAL] load file: " + str(param))

    # delete import info because they are not avarible anymore
    if hasattr(game.gdata, "import_info_key_in_old_scene"):
        del game.gdata.import_info_key_in_old_scene
    if hasattr(game.gdata, "import_info_new_to_old_key"):
        del game.gdata.import_info_new_to_old_key
    if hasattr(game.gdata, "import_info_old_to_new_key"):
        del game.gdata.import_info_old_to_new_key

    #print "arun_reloadprops persistent event scene_loaded"
    game.scenef_register_actorsprops()
    reloadVNText(game)
    reloadVNSound(game, False)
    reloadVNPhysics(game, False)
    if game.isSceneAutorunAnimDisabled: # we can disable VNAnime loading on current scene, needed only for old Scenes and VNs
        game.isSceneAutorunAnimDisabled = False
    else:
        reloadVNAnime(game, False)

    aiLoadSavedDHH(game)
    loadSavedGraphics(game)
    showDialogOnSceneLoad(game)

def scene_imported(game, eventid, param):
    """:type game: vngameengine.VNNeoController"""
    # kernel work
    #print("[KERNAL] import file: " + str(param))
    
    game.gdata.import_info_key_in_old_scene = list(game.studio.dicObjectCtrl.Keys)

def scene_imported_after(game, eventid, param):
    """:type game: vngameengine.VNNeoController"""
    # kernal work
    # kernal build a dict of dicKey for new imported ociObjects, to check its orignal dicKey
    # application should use this data from scene_imported_after2 event and deal with import data
    try:
        # get key change infomation from NodesConstraints plugin
        from extplugins import NodesConstraints
        nc = NodesConstraints()
        newToOld = nc.GetNewToOldKeys()
        # rebuild import info
        game.gdata.import_info_new_to_old_key = {}  # new imported key to key in org scene
        game.gdata.import_info_old_to_new_key = {}  # key in org scene which is updated to new key in current scene
        for newKey in list(game.studio.dicObjectCtrl.Keys):
            if newKey not in game.gdata.import_info_key_in_old_scene:
                oldKey = newToOld[newKey]
                game.gdata.import_info_new_to_old_key[newKey] = oldKey
                game.gdata.import_info_old_to_new_key[oldKey] = newKey
    except:
        # can not tracking dic key changing
        game.gdata.import_info_new_to_old_key = None
        game.gdata.import_info_old_to_new_key = None
        print("VNGE WARNING: Fail to get NewToOld info from NodesConstraints, dic key change is not tracked!")
        print("VNGE WARNING: This may cause some application fail to import data correctly!")

    # TODO: Should we tracking VNGE id conflict??
    game.scenef_register_actorsprops()

    # modules
    reloadVNText(game)
    reloadVNSound(game, True)
    reloadVNPhysics(game, True)
    reloadVNAnime(game, True)

def aiLoadSavedDHH(game):
    """:type game: vngameengine.VNNeoController"""
    if game.isNEOV2:
        from vngameengine import HSNeoOCIFolder
        fld = HSNeoOCIFolder.find_single_startswith("-vngedhhaisave:")
        if fld != None:
            try:
                import sceneutils
                sceneutils.ai_load_dhh(game)
            except Exception as e:
                print("VNGE: can't auto-load DHH settings: " + str(e))

def loadSavedGraphics(game):
    """:type game: vngameengine.VNNeoController"""
    if game.isNEOV2:
        from vngameengine import HSNeoOCIFolder
        fld = HSNeoOCIFolder.find_single_startswith("-vngegraphicssave:")
        if fld != None:
            try:
                import sceneutils
                sceneutils.load_graphics(game)
            except Exception as e:
                print("VNGE: can't auto-load Graphics settings: " + str(e))

def reloadVNText(game):
    """:type game: vngameengine.VNNeoController"""
    try:
        import vntext
        mgr = vntext.get_vntext_manager(game)
        mgr.reloadTextInfo()
        from vntext import vntxt_toolbar_update
        vntxt_toolbar_update()
    except Exception as e:
        print("reloadVNText exception during scene load/import: " + str(e))

def reloadVNSound(game, isImport):
    """:type game: vngameengine.VNNeoController"""

    def vnsound_later_bind(game, count):
        if count[0] > 0:
            count[0] -= 1
            return False
        else:
            vnsndmgr = vnsound.get_vnsound_manager(game)
            for ss in vnsndmgr.spectrumSetting:
                ss.initialize(game)
            print("VNSound spectrum setting initialized")
            return True

    try:
        import vnsound
        vnsound.scene_loaded_imported(game, isImport)

        vnsndmgr = vnsound.get_vnsound_manager(game)
        if vnsndmgr and len(vnsndmgr.spectrumSetting) > 0:
            later_bind_count = [5]
            game.append_update_job(vnsound_later_bind, later_bind_count)
    except Exception as e:
        print("reload VNSound exception during scene load/import: " + str(e))

def reloadVNPhysics(game, isImport):
    from vnphysics import initialize
    vnphy = initialize(game)

    if isImport:
        ret = vnphy.loadData(None, True, game.gdata.import_info_old_to_new_key)
        if ret:
            game.logger_log_message("vnPHY data imported as #%d, please check id changing!"%vnphy.appendCount, "VNPHY: ")
    else:
        vnphy.cleanup()
        vnphy.loadData()


def reloadVNAnime(game, isImport):
    """:type game: vngameengine.VNNeoController"""
    try:
        print("VNAnime Info: Auto initialize vnanime on scene %s"%("import..." if isImport else "load..."))
        import vnanime
        if isImport:
            vnanime.merge_imported_clips(game)
            vnanime.merge_imported_clips_png(game)
        # re-init
        vnanime.init_keyframe_anime(game)
        # start autorun clip
        vnanime.start_autorun_clips(game)
    except Exception as e:
        print("reloadVNAnime exception during scene load/import: " + str(e))

def showDialogOnSceneLoad(game):
    """:type game: vngameengine.VNNeoController"""
    from vngameengine import getEngineOptions
    from vngameengine import HSNeoOCIFolder
    from vngameengine import color_text,color_text_green,color_text_gray,color_text_yellowlight,color_text_red
    option = getEngineOptions()
    # check is option set up
    if "showdialogonsceneload" in option:
        if option["showdialogonsceneload"] == "1":

            if game.isTitleScreen: # only on title screen
                btns = []

                isData = False

                if HSNeoOCIFolder.find_single_startswith(":vnscenescript:") != None:
                    btns.append(color_text_green("Play VN Scene"))
                    btns.append(dlgPlayVNSS)
                    isData = True



                import scenesavestate
                if len(scenesavestate._sc.block) > 0:
                    btns.append("Open scenes in SSS editor")
                    btns.append(dlgPlaySSS)
                    isData = True
                else:
                    if HSNeoOCIFolder.find_single_startswith("-scenesavestate:") != None:
                        btns.append("Open scenes in SSS editor")
                        btns.append(dlgPlaySSS)
                        isData = True

                import vnanime
                if vnanime.check_keyframe_anime(game):
                    if len(game.gdata.kfaManagedClips) > 0:
                        arPlaying = [tgt for tgt in game.gdata.kfaManagedClips if game.gdata.kfaManagedClips[tgt].isPlaying]
                        btns.append("Open Keyframe Clip Man (animation playing {0}/{1})".format(len(arPlaying),len(game.gdata.kfaManagedClips)))
                        btns.append(dlgOpenClipMan)
                        isData = True


                # timeline work only after
                # print "Arun", exttimeline.isDetected
                # print "Arun", exttimeline.SceneContainsInterpolables()
                # if exttimeline.isDetected:
                #     if exttimeline.SceneContainsInterpolables():
                #         btns.append("Timeline: play/pause")
                #         btns.append(dlgTimelinePlayPause)
                #         isData = True

                # MMDD data
                try:
                    from extplugins import ExtensibleSaveFormat
                    esfPlugin = ExtensibleSaveFormat()
                    if esfPlugin.isDetected:
                        sData = esfPlugin.loadExtendSaveData("mmddirectorData")
                        if sData.version >= 2:
                            btns.append("Load with MMD Director")
                            btns.append(dlgOpenMMDD)
                            isData = True
                except:
                    pass

                if isData:
                    if game.visible:
                        btns.append(color_text_gray("return back"))
                        btns.append((dlgBack, True))
                    else:
                        game.visible = True
                        btns.append(color_text_gray("return back"))
                        btns.append((dlgBack, False))

                    game.set_text_s("<b>This scene contains VNGE data!</b>\nWhat to do?")
                    game.set_buttons_alt(btns)

def dlgPlayVNSS(game):
    """:type game: vngameengine.VNNeoController"""
    game.game_start_fromfile(game,"vnscenescriptrunview")

def dlgPlaySSS(game):
    """:type game: vngameengine.VNNeoController"""
    game.game_start_fromfile(game,"scenesavestate")

def dlgOpenClipMan(game):
    """:type game: vngameengine.VNNeoController"""
    game._sup_toggle_vnframe_console()

def dlgOpenMMDD(game):
    """:type game: vngameengine.VNNeoController"""
    game.game_start_fromfile(game,"mmddirector")

def dlgBack(game,param):
    """:type game: vngameengine.VNNeoController"""
    game.return_to_start_screen()
    game.visible = param

# def dlgTimelinePlayPause(game):
#     """:type game: vngameengine.VNNeoController"""
#     exttimeline.Play()
