const log = require('../../logging')
const InstanceCLI = require('../../clients/Instance')
const { readProfile } = require('../../profile')
const { v4: uuidv4 } = require('uuid')
const { basename } = require('path')
const MultiProgress = require('multi-progress')
const { uploadWithProgress } = require('../../upload')
const { waitForTaskState } = require('../../utils')

async function builder (yargs) {
  yargs
    .positional('instanceId', {
      type: 'string',
      describe: 'Instance id',
      demandOption: true
    })
    .positional('zipFile', {
      type: 'string',
      describe: 'Path to backup zip file',
      demandOption: true
    })
    .positional('password', {
      type: 'string',
      describe: 'Password for encrypted backup',
      demandOption: false
    })
    .option('verbose', {
      alias: 'v',
      type: 'boolean',
      describe: 'Console will receive verbose error output',
      demandOption: false
    })
}

async function handler (argv) {
  const profile = readProfile()
  const { instanceId, zipFile, password } = argv
  const name = basename(zipFile)
  const image = uuidv4()
  const url = profile.endpoint +
    '/api/v1/instances' +
    '/' +
    encodeURIComponent(instanceId) +
    '/' +
    'image-upload/backup' +
    '/' +
    encodeURIComponent(image) +
    '/' +
    encodeURIComponent(name)

  const multi = new MultiProgress(process.stderr)

  try {
    await uploadWithProgress(url, profile.token, zipFile, multi, {
      'x-corellium-image-encapsulated': 'false'
    })
    console.log(`Backup uploaded ${image}`)

    const instance = new InstanceCLI(argv)
    await instance.restoreBackup(password)

    await waitForTaskState(instanceId, instance.info.bind(instance), 'restoring-backup')
    console.log('Restoring in progress')
    await waitForTaskState(instanceId, instance.info.bind(instance), 'none')

    log.info(`Restored backup ${zipFile} to ${argv.instanceId}`)
  } catch (err) {
    const errorMessage = err.message
    log.error(`Restore backup failed: ${errorMessage}`)
    if (err.response && err.response.data && err.response.data.error) {
      log.error(err.response.data.error)
    }
    if (argv.verbose) { log.error(err) }
    process.exit(1)
  }
}

module.exports = {
  builder,
  handler,
  command: 'restore-backup <instanceId> <zipFile> [password] [--verbose]',
  describe: 'Restore iOS backup to instance'
}
