const {read} = require("../config").host("block")
const fetch = require("node-fetch")
const fs = require("fs")

const zip = async (api, {id, location = process.cwd(), output}) => {
  id = id || read(api.host, location).id
  const resp = await fetch(`${api.host}/api/block/${id}/zip`, {
    headers: {"Authorization": "Bearer " + api.token},
  })
  if(resp.status != 200) throw resp.statusText

  const stream = output == "-" || !output ? process.stdout : fs.createWriteStream(output)
  resp.body.pipe(stream)

}

const unzip = async (api, {filename}) => {
  const resp = await fetch(`${api.host}/api/block/unzip`, {
    method: "POST",
    headers: {"Authorization": "Bearer " + api.token, "Content-Type": "application/zip"},
    body: filename == "-" || !filename ? process.stdin : fs.createReadStream(filename)
  })
  if(resp.status != 200) {
    if(resp.headers.get('content-type') == "application/json") throw (await resp.json()).error
    throw await resp.text()
  }
  return await resp.json()
}

module.exports = {zip, unzip}
