const { getErrorMessage } = require('../../error')
const fs = require('fs')
const { displayTable } = require('../../table')
const { getApi } = require('../../utils')

async function builder (yargs) {
  yargs.option('project', {
    type: 'input',
    describe: 'Project Id',
    string: true
  })
    .option('format', {
      type: 'input',
      describe: 'Output format (default is table) e.g. json',
      string: true,
      choices: ['json', 'csv']
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output'
    })
    .option('instance', {
      type: 'input',
      describe: 'Instance Id',
      string: true
    })
    .positional('imageName', {
      type: 'string',
      describe: 'Image name',
      demandOption: true
    })
    .positional('imageType', {
      type: 'string',
      describe: 'Image type to upload',
      demandOption: true
    })
    .positional('encoding', {
      type: 'string',
      describe: 'Encoding, e.g. plain or encrypted'
    })
    .positional('file', {
      type: 'string',
      describe: 'Path to image file',
      demandOption: true
    })
}

async function handler (argv) {
  const imageType = argv.imageType
  const imagePath = argv.file
  const encoding = argv.encoding
  const imageName = argv.imageName
  const project = argv.project
  const instance = argv.instance
  const api = await getApi()

  const opts = {
    name: imageName,
    project: project,
    instance: instance,
    file: fs.createReadStream(imagePath)
  }

  try {
    const image = await api.v1CreateImage(imageType, encoding, opts)
    displayTable(argv.format, [image], ['status', 'id', 'name', 'type', 'project'])
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`Failed to create image: ${errorMessage}`)

    if (argv.detailedErrors) {
      console.log(error)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'create [project] [instance] <imageName> <imageType> <encoding> <file>',
  describe: 'Create image and optionally associate with a project/instance'
}
