
import { actionAddins } from ".";
import {  IAction,IActionResult, IActionNode, IActionProperty, IContext, IVarName } from "../types/ActionTypes";
import { ConditionTree } from '../types/Conditions';
/**
 * アクションの属性定義
 */
interface ICondition{
    condition:string;
    verName:IVarName;
}
/**
 * 条件分岐アクション
 */
export class ConditionAction implements IAction{
    name: string;
    actionProps: IActionProperty[];
    props:ICondition;
    constructor(){
        this.name="条件式";
        this.actionProps=[];
        this.props={
            condition:'',
            verName:{name:''}
        }
        //アクションを登録する
        this.register();
    }
    /**
     * アクションの実行を呼び出す
     * @param actionNode 
     * @param event 
     * @returns 
     */
    async process(actionNode:IActionNode,event:any,context:IContext):Promise<IActionResult> {
        let result={
            canNext:true,
            result:''
        };
        try{
            //属性設定を取得する
            this.actionProps=actionNode.actionProps;
            if (!('condition' in actionNode.ActionValue) && !('verName' in actionNode.ActionValue)) {
                return result
            }
            this.props = actionNode.ActionValue as ICondition;
            //条件式の計算結果を取得
            const conditionResult = this.getConditionResult(context);
            console.log("条件計算結果:",conditionResult);
            if(conditionResult){
                result= {
                    canNext:true,
                    result:'はい'
                  }
            }else{
                result= {
                    canNext:true,
                    result:'いいえ'
                  }
            }
            if(this.props.verName && this.props.verName.name!==''){
                context.variables[this.props.verName.name]=result.result;
            }
            return result;
        }catch(error){
            context.errors.handleError(error,actionNode);
            result.canNext=false;
            return result;
        }
    }
    /**
     * 
     * @param context 条件式を実行する
     * @returns 
     */
    getConditionResult(context:any):boolean{
        const tree =this.getCondition(this.props.condition);
        if(!tree){
            //条件を設定されていません
            return true;
        }
        return tree.evaluate(tree.root,context);
    }

    /**
     * @param condition 条件式ツリーを取得する
     * @returns 
     */
    getCondition(condition:string):ConditionTree|null{
        try{
            const tree = new ConditionTree();
            tree.fromJson(condition);
            if(tree.getConditions(tree.root).length>0){
                return tree;
            }else{
                return null; 
            }
        }catch(error){
            return null;
        }
    }

    register(): void {
        actionAddins[this.name]=this;
    }
    
}
new ConditionAction();