// LZMA imported from <script> in index.html
const blob = new Blob([
  'importScripts("https://cdn.jsdelivr.net/npm/lzma@2.3.2/src/lzma_worker.min.js");',
])
const lzma = new LZMA(window.URL.createObjectURL(blob))

async function compress(value: string): Promise<string> {
  return new Promise((resolve, reject) => {
    lzma.compress(value, 1, (numbers: number[]) => {
      const bytes = new Uint8Array(numbers)
      const b64 = btoa(String.fromCharCode(...bytes))
      resolve(b64)
    })
  })
}

async function decompress(base64: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const req = new XMLHttpRequest()
    req.open('GET', 'data:application/octet;base64,' + base64)
    req.responseType = 'arraybuffer'
    req.onload = (e) => {
      const bytes = new Uint8Array(req.response)
      lzma.decompress(bytes, (result, err) => {
        if (err) reject(err)
        else resolve(result)
      })
    }
    req.send()
  })
}

export { compress, decompress }
