#!/usr/bin/env node

// Packages
var GenerateSchema = require('../src/index')
var cli = require('commander')
var pkg = require('../package.json')
var fs = require('fs')

// Outputs
var content = ''
var mode = 'json'
var quiet = false
var file = null

// Setup CLI
cli.version(pkg.version)
cli.usage('[options ...] [file]')

cli.option('-q, --quiet', 'Skip help message in program output', function () { 
  quiet = true 
})

cli.option('-g, --generic', 'Generic JSON Primitives schema output', function () { 
  mode = 'generic' 
})

cli.option('-j, --json-schema', 'JSON Schema output', function () { 
  mode = 'json' 
})

cli.option('-m, --mongoose', 'Mongoose Schema output', function () {
  mode = 'mongoose'
})

cli.option('-s, --mysql, --sqlite', 'MySQL Table Schema output', function () {
  mode = 'mysql'
})

cli.option('-sq, --sqlite', 'SQLite Table Schema output', function () {
  mode = 'mysql'
})

cli.option('-b, --big-query', 'Google BigQuery Schema output', function () {
  mode = 'bigquery'
})

cli.option('-c, --clickhouse', 'ClickHouse Table Schema output', function () {
  mode = 'clickhouse'
})

cli.action(function (filename) {
  file = filename
})

cli.parse(process.argv)

// Program

function evaluate (data) {
  var obj

  try {
    obj = JSON.parse(data)
  } catch (e) {
    try {
      obj = eval('(' + data + ')')
    } catch (e) {
      console.log('Invalid Object or JSON')
    }
  }

  return obj
}

function prompt (motd) {
  if (motd && !quiet) {
    console.log('generate-schema', 'v' + pkg.version, '(' + mode + ')')
    console.log('Type', '"exit"', 'to quit.')
    console.log('Type', '{a:"b"}', 'to see an example.')
  }

  if (process.stdin.isTTY) {
    process.stdout.write('> ')
  }
}

function callback (data) {
  if (data.indexOf('exit') === 0) {
    return process.exit()
  }

  var obj
  obj = evaluate(data)
  obj = GenerateSchema[mode](obj)

  if (obj && typeof obj === 'object') {
    obj = JSON.stringify(obj, null, 2)
  }

  if (obj) {
    console.log(obj)
  }

  prompt()
}

var stream = process.stdin

if (file) {
  stream = fs.createReadStream(file)
  stream.on('close', function () {
    process.exit(1)
  })
}

stream.setEncoding('utf8')

if (!file) {
  prompt(true)

  stream.on('data', function (buf) {
    callback(buf.toString().trim())
  })
} else {
  stream.on('data', function (buf) {
    content += buf.toString()
  })

  stream.on('end', function () {
    console.log(JSON.stringify(GenerateSchema[mode](evaluate(content)), null, 2))
  })
}
