import { State } from '../store/rootReducer'

export const saveState = (state: object) => {
  try {
    const serializedState = JSON.stringify(state)

    localStorage.setItem('state', serializedState)
  } catch (err) {
    console.log(`Error while saving state. Error: `, err)
  }
}

export const loadState = (): State | undefined => {
  try {
    const serializedState = localStorage.getItem('state')

    if (serializedState === null) return undefined

    return JSON.parse(serializedState)
  } catch (err) {
    return undefined
  }
}

export const clearState = () => {
  localStorage.removeItem('state')
}

export const saveNsecBunkerDelegatedKey = (privateKey: string) => {
  localStorage.setItem('nsecbunker-delegated-key', privateKey)
}

export const getNsecBunkerDelegatedKey = () => {
  return localStorage.getItem('nsecbunker-delegated-key')
}

export const saveVisitedLink = (pathname: string, search: string) => {
  localStorage.setItem(
    'visitedLink',
    JSON.stringify({
      pathname,
      search
    })
  )
}

export const getVisitedLink = () => {
  const visitedLink = localStorage.getItem('visitedLink')
  if (!visitedLink) return null

  try {
    return JSON.parse(visitedLink) as {
      pathname: string
      search: string
    }
  } catch {
    return null
  }
}

export const saveAuthToken = (token: string) => {
  localStorage.setItem('authToken', token)
}

export const getAuthToken = () => {
  return localStorage.getItem('authToken')
}

export const clearAuthToken = () => {
  localStorage.removeItem('authToken')
}
