#!/usr/bin/env node
const fs = require('fs');
const { argv } = require('process');
const { throwError, getFile, getApiHtml } = require('./utils');
const ncp = require('ncp').ncp;
ncp.limit = 20;

process.env.OUTPUT_DIR = './dist'

const exec = async () => {
  const params = argv.slice(2).reduce((t, c) => {
    const lastIndex = t.length - 1;
    if (lastIndex >= 0 && t[lastIndex].name && !t[lastIndex].value) {
      t[lastIndex].value = c;
    } else {
      t.push({ name: c });
    }
    return t;
  }, []);

  let proxy;
  let body = {};

  for (let {name = '', value = ''} of params) {
    if (!name || !value) return throwError('Please provide correct parameters');
    
    if (name === '--url' || name === '-u') {
      body.url = value;
    } else if (name === '--file' || name === '-f') {
      body.source = await getFile(value);
    } else if (name === '--option' || name === '-o') {
      body.options = await getFile(value);
    } else if (name === '--version' || name === '-v') {
      body.version = value;
    } else if (name === '--yaml' || name === '-y') {
      body.yaml = parseInt(value);
    } else if (name === '--type' || name === '-t') {
      body.type = value;
    } else if (name === '--proxy' || name === '-p') {
      proxy = value;
    } else {
      return throwError(`Wrong parameter: ${name}`);
    }
  }

  if (!body.options) {
    body.options = await getFile('./options.json');
  }

  const { url = '', source = '', options = {} } = body;
  let { version = '2', type = 'swagger' } = body;
  
  if (version) { 
    version = parseInt(version);
    if (!(version >= 1 && version <= 3)) {
      return throwError('Please enter a valid value for version, like 1, 2, 3');
    }
  }

  if (!['swagger', 'openapi', 'api_blueprint', 'io_docs', 'google', 'raml', 'wadl'].includes(type)) {
    return throwError('Please enter a correct value for type, like swagger, openapi, api_blueprint, io_docs, google, raml or wadl');
  }

  if (!url && !source) return throwError('Invalid input source');

  let {logo = ''} = options || {};

  if (!fs.existsSync(process.env.OUTPUT_DIR)){
    fs.mkdirSync(process.env.OUTPUT_DIR);
  }

  if (logo) {
    const li = logo.lastIndexOf('/') + 1;
    const logoName = logo.substr(li);

    ncp(logo, `${process.env.OUTPUT_DIR}/${logoName}`, () => {});
    options.logo = logoName;
  }

  const finalHtml = await getApiHtml(JSON.stringify(body), proxy);
  fs.writeFileSync(`${process.env.OUTPUT_DIR}/index.html`, finalHtml);
}

exec();
