
import { actionAddins } from ".";
import {  IAction,IActionResult, IActionNode, IActionProperty, IField, IContext } from "../types/ActionTypes";

interface IMustInputProps{
    field:IField;
    message:string; 
}

export class MustInputAction implements IAction{
    name: string;
    actionProps: IActionProperty[];
    props:IMustInputProps;
    constructor(){
        this.name="必須チェック";
        this.actionProps=[];
        this.register();
        this.props={
            field:{code:''},
            message:''
        }
        this.register();
    }

    async process(actionNode:IActionNode,event:any,context:IContext):Promise<IActionResult> {
        let result={
            canNext:true,
            result:false
        };
        try{
            this.actionProps=actionNode.actionProps;
            if (!('field' in actionNode.ActionValue) && !('message' in actionNode.ActionValue)) {
                return result
            }
            this.props = actionNode.ActionValue as IMustInputProps;
            const record = event.record;
            if(!(this.props.field.code in record)){
                throw new Error(`フィールド[${this.props.field.code}]が見つかりませんでした。`);
            }
            const value = record[this.props.field.code].value;
            if(value===undefined || value===''){
                record[this.props.field.code].error=this.props.message;
                return result;
            }
            result= {
              canNext:true,
              result:true
            }
        }catch(error){
            context.errors.handleError(error,actionNode);
            result.canNext=false;
        }
        return result;
    }

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