import type { Field, FieldLayout, SavedData } from "@/types/model";
import { KintoneIndexEventHandler } from "./KintoneIndexEventHandler.mobile";

(function (PLUGIN_ID) {
  kintone.events.on('mobile.app.record.index.show', (event) => {
    try{
      const setting = kintone.plugin.app.getConfig(PLUGIN_ID);
      const config:SavedData<FieldLayout> = getConfig(setting);
      const currentApp = kintone.mobile.app.getId()?.toString();
      if(!currentApp) return;
      const handler = new KintoneIndexEventHandler(config,currentApp);
      handler.init();   
    }catch(error){
      const detailError =(error instanceof Error) ? "\n詳細:" + error.message : "";
      const errorMsg = `データ収集中処理中例外発生しました。${ detailError }`;
       event.error = errorMsg;  
    }
    return event;
  });
  /**
   * Config設定値を変換する
   * @param setting 
   * @returns 
   */
  function getConfig(setting:any):SavedData<FieldLayout>{
    const config:SavedData<FieldLayout>={
      buttonName:setting.buttonName,
      joinTables:JSON.parse(setting.joinTables)
    }
    return config;
}
})(kintone.$PLUGIN_ID);
