import { defineStore } from 'pinia'

export type Route = {
  name: string
  fullPath: string
}

export const useKeepAlive = defineStore('keepAlive', () => {
  const savedRoutes = ref<Route[]>(
    JSON.parse(sessionStorage.getItem('savedRoutes') ?? '[]')
  )
  const saveRoute = ({ name, fullPath }: Route) => {
    const index = savedRoutes.value.findIndex(
      savedRoute => savedRoute.name === name
    )
    if (index > -1) {
      savedRoutes.value[index] = { name, fullPath }
    } else {
      savedRoutes.value.push({ name, fullPath })
    }
    sessionStorage.setItem('savedRoutes', JSON.stringify(savedRoutes.value))
  }

  const cachedViews = ref<string[]>([])
  const addCachedView = (viewName: string) => {
    cachedViews.value.includes(viewName) || cachedViews.value.push(viewName)
  }
  const addCachedViewAll = (views: string[]) => {
    views.forEach(view => addCachedView(view))
  }
  const delCachedView = (viewName: string) => {
    const index = cachedViews.value.indexOf(viewName)
    index > -1 && cachedViews.value.splice(index, 1)
  }
  const delCachedViewUntil = (viewName: string) => {
    while (
      cachedViews.value.length &&
      cachedViews.value[cachedViews.value.length - 1] !== viewName
    ) {
      cachedViews.value.pop()
    }
  }
  const delCachedViewAll = () => {
    cachedViews.value = []
  }

  return {
    savedRoutes,
    saveRoute,
    cachedViews,
    addCachedView,
    addCachedViewAll,
    delCachedView,
    delCachedViewAll,
    delCachedViewUntil,
  }
})
