/* eslint-disable @typescript-eslint/no-explicit-any */
import { klona } from "klona/json"
import { get, set, toPath } from "lodash-es"
import { evaluateDynamicString } from "../evaluateDynamicString"
import { runEventHandler } from "../eventHandlerHelper"
import { IMPAKTAPPSEditorRuntimePropsCollectorInstance } from "../executionTreeHelper/runtimePropsCollector"
import { convertPathToString } from "../converter"
// import { NavigateFunction } from "react-router-dom"

export const runAllEventHandler = (
  events: any[] = [],
  dynamicAttrPaths: string[] = [],
  store,
  // navigate:NavigateFunction
  navigate:any
) => {
  const finalContext =
    IMPAKTAPPSEditorRuntimePropsCollectorInstance.getGlobalCalcContext({},store)
  const needRunEvents = klona(events).map((originEvent) => {
    return {
      ...originEvent,
      originEnable: originEvent.enabled,
    }
  })
  dynamicAttrPaths.forEach((path) => {
    const realPath = convertPathToString(toPath(path).slice(1))
    try {
      const dynamicString = get(needRunEvents, realPath, "")
      if (dynamicString) {
        const calcValue = evaluateDynamicString(
          `events${realPath}`,
          dynamicString,
          finalContext,
        )
        set(needRunEvents, realPath, calcValue)
      }
    } catch (e) {
      console.log(e)
    }
  })
  needRunEvents.forEach((scriptObj) => {
    runEventHandler(scriptObj, finalContext,store,navigate)
  })
}
