import maya.api.OpenMaya as om
import os
import json

from V2A.core import process

def maya_useNewAPI():
    pass

class Video2ARKitCommand(om.MPxCommand):
    COMMAND_NAME    = "v2aCmds"
    kVideoPath      = 'v'
    kVideoPathLong  = 'videoPath'
    kModelPath      = 'm'
    kModelPathLong  = 'modelPath'
    kOutputPath     = 'o'
    kOutputPathLong = 'outputPath'
    kReload         = 'r'
    kReloadLong     = 'reload'

    def __init__(self):
        om.MPxCommand.__init__(self)

    def createSyntax():
        syntax = om.MSyntax()
        syntax.addFlag("v", "videoPath", om.MSyntax.kString)
        syntax.addFlag("m", "modelPath", om.MSyntax.kString)
        syntax.addFlag("o", "outputPath", om.MSyntax.kString)
        syntax.addFlag("r", "reload", om.MSyntax.kString)
        
        return syntax
    
    def doIt(self, args):
        argData = om.MArgParser(self.syntax(), args)
        
        reload_object = None
        if argData.isFlagSet(self.kReload):
            # 重新加載快取
            node_name = argData.flagArgumentString("reload", 0)
            s_list = om.MGlobal.getSelectionListByName(node_name) if node_name else om.MGlobal.getActiveSelectionList()
            s_iter = om.MItSelectionList(s_list, om.MFn.kDependencyNode)
            if not s_iter.isDone():
                depend_node = s_iter.getDependNode()
                node_fn = om.MFnDependencyNode(depend_node)
                # 如果是 Video2ARKit 節點，觸發重新加載快取
                if node_fn.typeName == "Video2ARKit":
                    trigger = node_fn.findPlug("processTrigger", True)
                    value = trigger.getValue()
                    trigger.setValue(value)
        else:
            # 處理影片並返回快取結果
            if argData.isFlagSet("videoPath"):
                video_path = argData.flagArgumentString("videoPath", 0)
            model_path = os.getenv('V2A_MODEL_PATH')
            if argData.isFlagSet("modelPath"):
                model_path = argData.flagArgumentString("modelPath", 0)
            output_path = None
            if argData.isFlagSet("outputPath"):
                output_path = argData.flagArgumentString("outputPath", 0)
            if not video_path:
                om.MGlobal.displayError("Video path is required.")
                return
            if not model_path:
                om.MGlobal.displayError("Model path is required.")
                return
            if not output_path:
                om.MGlobal.displayInfo("No output path specified. Results will not be saved to file.")    
            else:
                om.MGlobal.displayInfo(f"Output path set to: {output_path}")
                
            om.MGlobal.displayInfo(f"Processing video: {video_path} with model: {model_path}")
            cache = process.process_video(video_path, model_path, output_path)
            if not output_path:
                super(Video2ARKitCommand, self).setResult(json.dumps(cache))
            else:
                om.MGlobal.displayInfo(f"Output path set to: {output_path}")
                # super(Video2ARKitCommand, self).setResult(json.dumps(cache))

        # om.MGlobal.displayInfo("Video2ARKit processing command executed.")

    @staticmethod
    def creator():
        return Video2ARKitCommand()