#!/usr/bin/env node

'use strict'

var chalk = require('chalk')
var cmd = require('commander')
var fs = require('fs')
var readFile = require('fs-readfile-promise')
var writeFile = require('fs-writefile-promise')
var HTTPSnippet = require('..')
var path = require('path')
var pkg = require('../package.json')

cmd
  .version(pkg.version)
  .usage('[options] <files ...>')
  .option('-t, --target <target>', 'target output')
  .option('-c, --client [client]', 'target client library')
  .option('-o, --output <directory>', 'write output to directory')
  .parse(process.argv)

if (!cmd.args.length || !cmd.target) {
  cmd.help()
}

if (cmd.output) {
  var dir = path.resolve(cmd.output)

  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir)
  }
}

cmd.args.forEach(function (fileName) {
  var file = path.basename(fileName)

  readFile(fileName)
    .then(JSON.parse)

    .catch(function (e) {
      console.error('%s %s failed to read JSON: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message))
    })

    .then(function (data) {
      return new HTTPSnippet(data)
    })

    .catch(function (e) {
      e.errors.forEach(function (err) {
        console.error('%s %s failed validation: (%s: %s) %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.cyan.italic(err.field), chalk.magenta.italic(err.value), chalk.red(err.message))
      })
    })

    .then(function (snippet) {
      return snippet.convert(cmd.target, cmd.client)
    })

    .then(function (output) {
      // print
      if (!cmd.output) {
        return console.log('%s %s > %s [%s] :\n%s', chalk.green('✓'), chalk.cyan.bold(file), chalk.yellow(cmd.target), chalk.yellow(cmd.client ? cmd.client : 'default'), output)
      }

      // write to file
      var name = path.basename(file, path.extname(file))

      var filename = path.format({
        dir: dir,
        base: name + HTTPSnippet.extname(cmd.target)
      })

      return writeFile(filename, output + '\n', function () {
        console.log('%s %s > %s', chalk.green('✓'), chalk.cyan.bold(file), filename)
      })
    })

    .catch(function (e) {
      console.error('%s %s fail: %s', chalk.red('✖'), chalk.cyan.bold(file), chalk.red(e.message))
    })
})
