import $ from 'jquery';
import { ActionProcess } from './types/action-process';
import { ActionFlow } from './types/ActionTypes';
import { FlowInfo } from './types/flowSetting';

declare const alcflow : {
  [key:string]:FlowInfo
};

$(function (){
    const getChangeEvents=(events:string[])=>{
      return events.filter((event)=>event.includes(".change."));
    }
    const getClickEvents=(events:string[])=>{
      return events.filter((event)=>event.includes(".customButtonClick."));
    }
    const getKintoneEvents=(events:string[])=>{
      return events.filter((event)=>{
        return !event.includes(".customButtonClick.") && !event.includes(".change.")
      });
    }
    const events=Object.keys(alcflow);
    const changeEvents = getChangeEvents(events);
    const clickEvents = getClickEvents(events);
    const kintoneEvents = getKintoneEvents(events);
    if(kintoneEvents.length>0 ){
      //通常Kintoneイベントをバンド
      kintone.events.on(kintoneEvents,async (event:any)=>{
        const flowinfo = alcflow[event.type];
        const flow=ActionFlow.fromJSON(flowinfo.content);
        if(flow!==undefined){
          const process = new ActionProcess(event.type,flow,event);
          await process.exec();
        }
        return event;
      });
    }
    if(changeEvents.length>0){
      //値変更イベントをバンドする
      kintone.events.on(changeEvents,(event:any)=>{
        const flowinfo = alcflow[event.type];
        const flow=ActionFlow.fromJSON(flowinfo.content);
        if(flow!==undefined){
          const process = new ActionProcess(event.type,flow,event);
          process.exec().then((res)=>{
            const record = event.record;  
            kintone.app.record.set({record});
          }).catch((err)=>{
            console.error(err);
          });
        }
        return event;
      });
    }
    if(clickEvents.length>0){
      clickEvents.forEach((eventName:string)=>{
        $(document).on(eventName,async ()=>{
          const event=kintone.app.record.get();
          const flowinfo = alcflow[eventName];
          const flow=ActionFlow.fromJSON(flowinfo.content);
          if(flow!==undefined){
            const process = new ActionProcess(eventName,flow,event);
            await process.exec();
          }
          const record = event.record;
          kintone.app.record.set({record});
        });
      });
    }
});