const { readProfile } = require('../../profile')
const fs = require('fs')
const asciiArt = require('ascii-art')
const { getAxios } = require('../../utils')

async function builder (yargs) {
  yargs.positional('extensionJson', {
    type: 'string',
    describe: 'Path to extension json',
    demandOption: true
  }).option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  })
}

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

  const extensionJsonPath = argv.extensionJson

  const extensionsUrl = profile.endpoint + '/api/v1/extensions/parse/extension.json'

  try {
    const extensionJson = JSON.parse(fs.readFileSync(extensionJsonPath).toString())
    const axios = await getAxios()
    const res = await axios.post(extensionsUrl, extensionJson)

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

    console.log(
      asciiArt.style('Valid', 'green', true)
    )
  } catch (error) {
    if (argv.detailedErrors) {
      console.log(error)
    }

    if (error &&
        error.response &&
        error.response.data &&
        error.response.data.errors) {
      error.response.data.errors.forEach(e => {
        console.log(
          asciiArt.style(`${e.field} - ${e.error}`, 'red', true)
        )
      })
    } else {
      const errorMessage = error.message || error
      console.error(`Extension validate failed: ${errorMessage}`)
    }
  }
}

module.exports = {
  builder,
  handler,
  command: 'validate <extensionJson>',
  describe: 'Validate extension json'
}
