import {
  IAction,
  IActionResult,
  IActionNode,
  IActionProperty,
  IContext,
} from "../types/ActionTypes";
import { actionAddins } from ".";
// import { KintoneRestAPIClient } from "@kintone/rest-api-client";
// import { getPageState } from "../util/url";
import { Snipper } from '../util/ui-helper';
import { DropDownManager,ICascadingDropDown, IFieldList} from '../types/CascadingDropDownManager'
import "./cascading-dropdown.scss";
// import { Record as KTRecord } from "@kintone/rest-api-client/lib/src/client/types";

// 階層化ドロップダウンメニューのプロパティインターフェース
interface ICascadingDropDownProps {
  displayName: string;
  cascadingDropDown: ICascadingDropDown;
}

/**
 * 階層化ドロップダウンのクラス実装
 */
export class CascadingDropDownAction implements IAction {
  name: string;
  actionProps: IActionProperty[];
  props: ICascadingDropDownProps;

  constructor() {
    this.name = "階層化ドロップダウン";
    this.actionProps = [];
    this.props = {} as ICascadingDropDownProps;
    this.register();
  }

  /**
   * アクションのプロセス実行
   * @param actionNode 
   * @param event 
   * @param context 
   * @returns 
   */
  async process(
    actionNode: IActionNode,
    event: any,
    context: IContext
  ): Promise<IActionResult> {
    this.actionProps = actionNode.actionProps;
    this.props = actionNode.ActionValue as ICascadingDropDownProps;

    const result: IActionResult = { canNext: true, result: "" };
    const snipper = new Snipper("body");
    const dropDownManager= new DropDownManager(this.props.cascadingDropDown,event);
    try {
      if (!this.props) return result;
      const appId = this.props.cascadingDropDown.dropDownApp.id;
      //snipper表示
      snipper.showSpinner();
      await dropDownManager.handlePageState(appId);
      snipper.hideSpinner();
      return result;
    } catch (error) {
      console.error(
        "CascadingDropDownAction プロセス中にエラーが発生しました:",
        error
      );
      context.errors.handleError(error, actionNode);
      return { canNext: false, result: "" };
    }finally{
      snipper.removeSpinner();
    }
  }

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

new CascadingDropDownAction();
