import { Route } from 'vue-router'

export const RouteHelper = {
  saveWidgetLocation(route: Route): void {
    localStorage.setItem(
      this.getWidgetName(route),
      this.getStringifyRoute(route)
    )
  },

  getWidgetLocation(route: Route): Route | undefined {
    const savedRoute = localStorage.getItem(this.getWidgetName(route))

    return savedRoute ? JSON.parse(savedRoute) : undefined
  },

  saveLastLocation(route: Route): void {
    localStorage.setItem('last_location', this.getStringifyRoute(route))
  },

  getLastLocation(): Route | undefined {
    const savedRoute = localStorage.getItem('last_location')

    return savedRoute ? JSON.parse(savedRoute) : undefined
  },

  getWidgetName(route: Route) {
    return (route.name?.split('/') || [''])[0]
  },

  getStringifyRoute(route: Route): string {
    return JSON.stringify({
      path: route.path,
      name: route.name,
      hash: route.hash,
      query: route.query,
      params: route.params,
      fullPath: route.fullPath,
    })
  },
}
