
import { actionAddins } from "../actions";
import '../actions/must-input';
import '../actions/auto-numbering';
import '../actions/field-shown';
import '../actions/error-show';
import '../actions/button-add';
import '../actions/condition-action';
import '../actions/data-processing';
import '../actions/data-update';
import '../actions/current-field-get';
import '../actions/regular-check';
import '../actions/mail-check';
import '../actions/counter-check';
import '../actions/datetime-getter';
import '../actions/insert-value';
import '../actions/value-getter';
import '../actions/string-join';
import '../actions/validation-fullwidth';
import '../actions/validation-halfwidth';
import '../actions/half-full-conversion';
import '../actions/login-user-getter';
import '../actions/auto-lookup';
import '../actions/field-disable';
import '../actions/style-field';
import '../actions/datetime-calc';
import '../actions/end-of-month';
import '../actions/date-specified';
import '../actions/cascading-dropdown';
import { ActionFlow,ErrorManager,IActionFlow, IActionResult,IContext } from "./ActionTypes";
const ShowErrorEvents:string[] = [
    "app.record.create.submit.success",
    "app.record.edit.submit.success",
    "app.record.index.edit.submit.success",
  ];
export class ActionProcess{
    eventId:string;
    flow:IActionFlow;
    event:any;
    context:IContext;
     constructor(eventId:string,flow:ActionFlow,event:any){
        this.eventId=eventId;
        this.flow=flow;
        this.event=event;
        const errormanager = new ErrorManager();
 
        this.context={
            record:this.event.record,
            variables:{},
            errors:errormanager
        };
    }
    async exec(){
        const root = this.flow.getRoot();
        if(root===undefined || root.nextNodeIds.size===0){
            return;
        }
        let id=root.nextNodeIds.get('');
        if(id===undefined) return;
        let nextAction = this.flow.findNodeById(id); 
        let result:IActionResult={
            canNext:true
        };
        while(nextAction!==undefined && result.canNext){
           const action = actionAddins[nextAction.name];
           if(action!==undefined){
            result = await action.process(nextAction,this.event,this.context);
           }
           let nextInput = '';
           //outputPoints一つ以上の場合、次のInputPointは戻り値を設定する
           if(nextAction.outputPoints && nextAction.outputPoints.length>1){
             nextInput = result.result||'';
           }
           id=nextAction.nextNodeIds.get(nextInput);
           if(id===undefined) break;
           nextAction = this.flow.findNodeById(id); 
        }
        if(this.context.errors.hasError){
            this.context.errors.setEvent(this.event); 
            if(ShowErrorEvents.includes(this.event.type)){
                this.context.errors.showError();
            }    
        }
    }
}