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

interface Props {
  displayName: string;
  sources: Sources;
  dataMapping: DataMapping[];
}

interface DataMapping {
  id: string;
  from: From;
  to: To;
}

interface To {
  app: App;
  fields: Field[];
  isDialogVisible: boolean;
}

interface Field {
  name: string;
  type: string;
  code: string;
  label: string;
  noLabel: boolean;
  required: boolean;
  minLength: string;
  maxLength: string;
  expression: string;
  hideExpression: boolean;
  unique: boolean;
  defaultValue: string;
}

interface From {
  sharedText: string;
  _t: string;
  id: string;
  objectType: string;
  name: Name;
  actionName: string;
  displayName: string;
}

interface Name {
  name: string;
}

interface Sources {
  app: App;
}

interface App {
  id: string;
  name: string;
  description: string;
  createdate: string;
}

export class DataMappingAction implements IAction {
  name: string;
  actionProps: IActionProperty[];
  dataMappingProps: Props;
  constructor() {
    this.name = "データマッピング";
    this.actionProps = [];
    this.dataMappingProps = {} as Props;
    this.register();
  }

  async process(
    prop: IActionNode,
    event: any,
    context: IContext
  ): Promise<IActionResult> {
    this.actionProps = prop.actionProps;
    this.dataMappingProps = prop.ActionValue as Props;
    console.log(prop.ActionValue);
    
    // this.initTypedActionProps();
    let result = {
      canNext: true,
      result: "",
    } as IActionResult;
    try {
      for (const item of this.dataMappingProps.dataMapping) {
        if (item.from.objectType === "variable") {
          if (
            item.from.name.name &&
            item.to.app &&
            item.to.fields &&
            item.to.fields.length > 0
          ) {
            const value = getValueByPath(
              context.variables,
              item.from.name.name
            );
            if (value) {
              await kintone.api(
                kintone.api.url("/k/v1/record.json", true),
                "POST",
                {
                  app: item.to.app.id,
                  record: {
                    [item.to.fields[0].code]: {
                      value: value,
                    },
                  },
                }
              );
            }
          }
        }
      }
    } catch (error) {
      console.error("DataMappingAction error", error);
      result.canNext = false;
    }
    console.log("dataMappingProps", this.dataMappingProps);

    return result;
  }

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

new DataMappingAction();

const getValueByPath = (obj: any, path: string) => {
  return path.split(".").reduce((o, k) => (o || {})[k], obj);
};

type Resp = { records: RespRecordType[] };

type RespRecordType = {
  [key: string]: {
    type: string;
    value: any;
  };
};

type Result = {
  type: string;
  value: any[];
};

const selectData = async (appid: string, field: string): Promise<Result> => {
  return kintone
    .api(kintone.api.url("/k/v1/records", true), "GET", {
      app: appid ?? kintone.app.getId(),
      fields: [field],
    })
    .then((resp: Resp) => {
      const result: Result = { type: "", value: [] };
      resp.records.forEach((element) => {
        for (const [key, value] of Object.entries(element)) {
          if (result.type === "") {
            result.type = value.type;
          }
          result.value.push(value.value);
        }
      });
      return result;
    });
};
