export function truncate(value: string, length: number) {
  if (value.length > length) {
    return value.substring(0, length) + '...'
  } else {
    return value
  }
}

const language = localStorage.getItem('language') || 'en-us'

export function abbreviate(text: number) {
  return Intl.NumberFormat(language, {
    //@ts-ignore
    notation: 'compact',
    maximumFractionDigits: 1
  }).format(text)
}

const https = import.meta.env.SAFETWITCH_HTTPS.slice() === 'true'
const protocol = https ? 'https://' : 'http://'
const rootBackendUrl = `${protocol}${import.meta.env.SAFETWITCH_BACKEND_DOMAIN}/`

export async function getEndpoint(endpoint: string) {
  const res = await fetch(rootBackendUrl + endpoint, {
    method: 'GET',
    headers: {
      'Accept-Language': language
    }
  })
  const rawData = await res.json()

  if (!res.ok) {
    throw res
  }
  if (rawData.status !== 'ok') {
    throw rawData
  }

  const data = rawData.data

  return data
}

export function getTimeFromQuery(query: string) {
  //   H, M, S
  const x = query.split(/[^0-9.]/g);
  const times = x.map(Number)

  let time = 0
  time += times[0] * 3600
  time += times[1] * 60
  time += times[2]
  return time
}