import { defineStore } from 'pinia';
import { AppInfo, IActionFlow, IActionNode } from 'src/types/ActionTypes';
import { IKintoneEvent, KintoneEventManager, kintoneEvent } from 'src/types/KintoneEvents';
import { FlowCtrl } from '../control/flowctrl';

export interface FlowEditorState {
  flowNames1: string;
  appInfo?: AppInfo;
  flows?: IActionFlow[];
  selectedFlow?: IActionFlow | undefined;
  activeNode: IActionNode | undefined;
  eventTree: KintoneEventManager;
  selectedEvent: IKintoneEvent | undefined;
  expandedScreen: string[];
}
const flowCtrl = new FlowCtrl();
const eventTree = new KintoneEventManager();
export const useFlowEditorStore = defineStore('flowEditor', {
  state: (): FlowEditorState => ({
    flowNames1: '',
    appInfo: undefined,
    flows: [],
    selectedFlow: undefined,
    activeNode: undefined,
    eventTree: eventTree,
    selectedEvent: undefined,
    expandedScreen: [],
  }),
  getters: {
    /**
     *
     * @returns 現在編集しているフロー
     */
    currentFlow(): IActionFlow | undefined {
      return this.selectedFlow;
    },
    /**
     * KintoneイベントIDから、バンドしているフローを検索する
     * @param state
     * @returns
     */
    findFlowByEventId(state) {
      return (eventId: string) => {
        return state.flows?.find((flow) => {
          const root = flow.getRoot();
          return root?.name === eventId;
        });
      };
    },

    findEventById(state) {
      return (eventId: string) => {
        return state.eventTree.findEventById(eventId);
      };
    },

  },

  actions: {
    setFlows(flows: IActionFlow[]) {
      this.flows = flows;
    },
    selectFlow(flow: IActionFlow | undefined) {
      this.selectedFlow = flow;
      if(flow!==undefined){
        const eventId = flow.getRoot()?.name;
        this.selectedEvent = this.eventTree.findEventById(eventId) as IKintoneEvent;
      } else {
        this.selectedEvent = undefined;
      }
    },
    setActiveNode(node: IActionNode) {
      this.activeNode = node;
    },
    setCurrentEvent(event:IKintoneEvent | undefined){
      this.selectedEvent=event;
    },
    setApp(app: AppInfo) {
      this.appInfo = app;
    },
    /**
     * DBからフルーを保存する
     * @returns
     */
    async loadFlow() {
      if (this.appInfo === undefined) return;
      const actionFlows = await flowCtrl.getFlows(this.appInfo?.appId);
      //eventTreeにバンドする
      this.eventTree.bindFlows(actionFlows);
      if (actionFlows === undefined || actionFlows.length === 0) {
        this.setFlows([]);
        this.selectFlow(undefined);
        this.expandedScreen =[];
        return;
      }
      this.setFlows(actionFlows);
      if (actionFlows && actionFlows.length > 0) {
        this.selectFlow(actionFlows[0]);
      }
      const root = actionFlows[0].getRoot();
      if (root) {
        this.setActiveNode(root);
      }

      const expandEventIds = actionFlows.map((flow) => flow.getRoot()?.name);
      const expandScreens:string[]=[];
      expandEventIds.forEach((eventid)=>{
        const eventNode=this.eventTree.findEventById(eventid||'');
        if(eventNode){
          expandScreens.push(eventNode.parentId);
          if(eventNode.header==='DELETABLE'){
            const groupEvent = this.eventTree.findEventById(eventNode.parentId);
            if(groupEvent){
              expandScreens.push(groupEvent.parentId);
            }
          }
        }
      });
      // const expandName =actionFlows[0].getRoot()?.title;
      this.expandedScreen = expandScreens;
    },
    /**
     * フローをDBに保存及び更新する
     */
    async saveFlow(flow: IActionFlow):Promise<boolean> {
      const root = flow.getRoot();
      const isNew = flow.id === '';
      const jsonData = {
        flowid: isNew ? flow.createNewId() : flow.id,
        appid: this.appInfo?.appId,
        appname: this.appInfo?.name,
        eventid: root?.name,
        name: root?.subTitle,
        content: JSON.stringify(flow),
      };

      if (isNew) {
        return await flowCtrl.SaveFlow(jsonData);
      } else {
        if(flow.actionNodes.length>1){
          return await flowCtrl.UpdateFlow(jsonData);
        }else{
          const eventId = flow.getRoot()?.name||'';
          const eventNode = eventTree.findEventById(eventId) as kintoneEvent;
          eventNode.flowData=undefined;
          return await flowCtrl.DeleteFlow(flow.id);
        }
      }
    },


    async deleteEvent(event: IKintoneEvent) {
      const store = useFlowEditorStore();
      if (event.flowData) {
        const flow = event.flowData;
        if (flow.id !== '') {
          await flowCtrl.DeleteFlow(flow.id)
          if (this.flows) {
            this.flows = this.flows.filter((f) => f.id !== flow.id);
          }
        }
        eventTree.deleteEvent(event, store);
      }
      else {
        eventTree.deleteEvent(event, store);
      }
    },
    /**
     * デプロイする
     */
    async deploy(): Promise<boolean> {
      if (this.appInfo === undefined) {
        return false;
      }
      return await flowCtrl.depoly(this.appInfo?.appId);
    },
  },
});
