const { readProfile } = require('../../profile')
const { v4: uuidv4 } = require('uuid')
const { basename } = require('path')
const MultiProgress = require('multi-progress')
const { uploadWithProgress } = require('../../upload')
const { existsSync } = require('fs')
const { getErrorMessage } = require('../../error')

async function builder (yargs) {
  yargs.positional('files', {
    type: 'string',
    describe: 'One or more firmware file paths',
    demandOption: true
  }).option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  })
}

async function handler (argv) {
  const profile = readProfile()

  const multi = new MultiProgress(process.stderr)

  const files = argv.files

  await Promise.all(files.map(async (file) => {
    if (!existsSync(file)) {
      console.error('File does not exist: ', file)
      return
    }

    const fileName = basename(file)
    const imageId = uuidv4()
    const url = profile.endpoint +
      `/api/v1/domain/image-upload/fw/${imageId}/${encodeURIComponent(fileName)}`

    try {
      await uploadWithProgress(url, profile.token, file, multi)
      console.log(`Firmware uploaded ${imageId}`)
    } catch (error) {
      const errorMessage = error.message || getErrorMessage(error)
      console.error(`Firmware load failed: ${errorMessage}`)

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

module.exports = {
  builder,
  handler,
  command: 'load <files..>',
  describe: 'Load firmware files'
}
