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


interface ICurrentFieldGetProps {
  displayName: string;
  field: IField;
  verName: VerName;
}

interface VerName {
  name: string;
}


export class CurrentFieldGetAction implements IAction {
  name: string;
  actionProps: IActionProperty[];
  props: ICurrentFieldGetProps;
  constructor() {
    this.name = "フィールドの値を取得する";
    this.actionProps = [];
    this.props = {} as ICurrentFieldGetProps;
    this.register();
  }

  async process(
    actionNode: IActionNode,
    event: any,
    context: IContext
  ): Promise<IActionResult> {
    this.props = actionNode.ActionValue as ICurrentFieldGetProps;
    this.actionProps = actionNode.actionProps;

    let result = {
      canNext: true,
      result: '',
    } as IActionResult;
    
    try {
      const record = event.record;
      if(!(this.props.field.code in record)){
        throw new Error(`フィールド[${this.props.field.code}]が見つかりませんでした。`);
      }
      //変数設定
      if(this.props.verName && this.props.verName.name!==''){
        context.variables[this.props.verName.name]=record[this.props.field.code].value;
      }
    } 
    catch (error) {
      context.errors.handleError(error,actionNode);
      result.canNext = false;
    }
    return result;
  }

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

new CurrentFieldGetAction();
