import { refreshAccessToken } from '@/api/login'

const TokenKey = 'Admin-Token'
const RefreshTokenKey = 'Admin-RefreshToken'
const ExpiresKey = 'Admin-Expires'

export function getRefreshToken(){
  return sessionStorage.getItem(RefreshTokenKey)
}
export function setRefreshToken(refreshToken){
  return sessionStorage.setItem(RefreshTokenKey,refreshToken)
}
export function isRefreshTokenExpired(timestamp) {
  clearInterval(window.interval);
  window.interval = setInterval(()=>{
    timestamp=timestamp-60
    setExpires(timestamp)
    if (timestamp < 2000){
      let refreshToken = getRefreshToken();
      if (refreshToken){
          refreshAccessToken(refreshToken).then(res => {
            setToken(res.access_token)
            setRefreshToken(res.refresh_token)
            isRefreshTokenExpired(res.expires_in)
          }).catch(() => {})
        }

    }
  },1000 * 60)
}
export function setExpires(time){
  return sessionStorage.setItem(ExpiresKey, time)
}
export function getExpires(){
  return sessionStorage.getItem(ExpiresKey)
}
export function getToken() {
  return sessionStorage.getItem(TokenKey)
}

export function setToken(token) {
  return sessionStorage.setItem(TokenKey, token)
}

export function removeToken() {
  sessionStorage.removeItem(ExpiresKey)
  sessionStorage.removeItem(RefreshTokenKey)
  return sessionStorage.removeItem(TokenKey)
}
