import { is } from '@/utils/is'

export function getToken(): string | null {
  return window.localStorage.getItem('token')
}

export function setToken(token: string): void {
  window.localStorage.setItem('token', token)
}

export function removeToken(): void {
  window.localStorage.removeItem('token')
}

export async function getAsyncResult<T>(
  value: T | Promise<T> | (() => T) | (() => Promise<T>) | undefined,
  defaultValue: T
): Promise<T> {
  if (value === null || value === undefined) {
    return new Promise<T>((resole) => {
      resole(defaultValue)
    })
  }

  if (is(value, 'AsyncFunction')) {
    return await (value as Function)()
  }

  if (is(value, 'Promise')) {
    return value as Promise<T>
  }

  return new Promise<T>((resole) => {
    if (is(value, 'Function')) {
      resole((value as Function)())
    } else {
      resole(value as T)
    }
  })
}

export function getResult<T>(value: T | ((...params: any[]) => T), ...params: any[]): T {
  if (is(value, 'Function')) {
    return (value as Function)(...params)
  }
  return value as T
}
