const Logger = require("./Logger");
const fetch = require("node-fetch");

function parse(ref) {
  const matches = ref.match(/^gs:\/\/(\w[\w.-]+)\/((?:\w[\w.-]*)(?:\/\w[\w.-]*)*)$/)
  if(!matches) return null;
  const [, bucketName, path] = matches;
  return {bucketName, path};
}

function ref2url(ref) {
  const refo = parse(ref);
  if(!refo) throw "Invalid reference";
  const {bucketName, path} = refo;
  return `http://${bucketName}.storage.googleapis.com/${path}`;
}

ref2url.cli = yargs => yargs.command({
  command: "ref",
  desc: "Reference support",
  builder: yargs => yargs.command({
    command: "geturl <ref>",
    desc: "Convert ref to http url",
    handler: Logger.wrap(async ({ref}) => ref2url(ref))
  }).command({
    command: "download <ref>",
    desc: "Download content by ref",
    builder: yargs => yargs.option("content-type", {boolean: true, desc: "show content-type to stderr"}),
    handler: Logger.wrap(async ({ref, "content-type": contentType}) => {
      const resp = await fetch(ref2url(ref));
      contentType && console.error(resp.headers.get("content-type"));
      resp.body.pipe(process.stdout)
    }),
  }),
  handler() {yargs.showHelp()}
});

module.exports = ref2url;
