import { NavigationGuard } from 'vue-router'
import { getModule } from 'vuex-module-decorators'
import { HashNavigationModule } from '@/widgets/HashNavigationModule'
import { Store } from 'vuex'
import { HashNavRoute } from '@/widgets/base/types/HashNavRoute'

export function hashNavigationHookFactory<S, N extends string>(
  store: Store<S>,
  hashNavRoutes: HashNavRoute<N>[]
): NavigationGuard {
  const findMatchingEntryAndProps = (hash: string) => {
    for (const hashNavEntry of hashNavRoutes) {
      const data = hashNavEntry.match(hash)

      if (data) {
        return {
          layoutName: hashNavEntry.layoutName,
          pageName: hashNavEntry.pageName,
          props: data,
        }
      }
    }

    return null
  }

  return (to, from, next) => {
    if (!to.hash && from.hash) {
      const { name, ...toRest } = to

      return next({ ...toRest, hash: from.hash, replace: true })
    }

    next()

    const entryAndProps = findMatchingEntryAndProps(to.hash)
    const module = getModule(HashNavigationModule, store)

    if (entryAndProps) {
      module.setParams(entryAndProps)
    } else {
      module.setParams({ layoutName: null, pageName: null, props: {} })
    }
  }
}
