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

async function builder (yargs) {
  yargs.option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  }).option('format', {
    type: 'input',
    describe: 'Output format (default is table) e.g. json',
    string: true,
    choices: ['json', 'csv']
  })
}

async function handler (argv) {
  const api = await getApi()
  try {
    const models = await api.v1GetModels()
    const firmwareByModels = await Promise.all(models.map(async ({ model }) => {
      try {
        return await api.v1GetModelSoftware(model)
      } catch (error) {
        if (argv.detailedErrors) {
          console.log(error)
        }
      }
    }))

    const firmwareMap = new Map()
    firmwareByModels.forEach(firmwareByModel => {
      if (firmwareByModel === undefined || firmwareByModel.length === 0) {
        return
      }
      firmwareByModel.forEach(firmware => {
        if (!firmwareMap.has(firmware.sha256sum)) {
          firmwareMap.set(firmware.sha256sum, firmware)
        }
      })
    })

    const firmwares = Array.from(firmwareMap.values())
    displayTable(argv.format, firmwares, [
      'buildid', 'filename', 'size', 'version'
    ], [{ column: 0, width: 7 }, { column: 1, width: 8 }, { column: 3, width: 7 }])
  } catch (error) {
    const errorMessage = getErrorMessage(error)
    console.error(`List failed: ${errorMessage}`)

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

module.exports = {
  builder,
  handler,
  command: 'list',
  describe: 'List all firmware'
}
