"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getOptions = void 0;

var _child_process = require("child_process");

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _defaultConfigValues = _interopRequireDefault(require("./defaultConfigValues.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// import { argv } from 'process';
const args = process.argv.slice(2); // console.log('argv', argv);

const NPM_CONFIG_PREFIX = 'npm_config_'; // TODO: we have to do option parse logic little better
// if user use react-cli stritly without using npm scripts options won't work,
//  So  we have to write our own option parse logic or some other library
// console.log('type', process.argv,  process.env.npm_config_check,  process.env.npm_config_clone_type, process.env.npm_config_clone_url);
// console.log('Object.keys(process.env).filter(s => s.startsWith(\'npm_config_\') && s.includes(\'clone\')', Object.keys(process.env).filter(s => s.startsWith('npm_config_') && s.includes('clone')));
// // clone:type

const processEnv = {};
let keysWithColon = [];
Object.keys(process.env).filter(key => key.startsWith(NPM_CONFIG_PREFIX)).forEach(key => {
  let nkey = key.slice(NPM_CONFIG_PREFIX.length);
  processEnv[nkey] = process.env[key];
  nkey.includes(':') && keysWithColon.push(nkey);
});
keysWithColon.forEach(key => {
  let nkey = key.replace(/:/g, '_');

  if (processEnv[nkey]) {
    throw Error('there is some options conflict', key, nkey);
  }

  processEnv[nkey] = processEnv[key];
});

function getNpmVersion() {
  // require("child_process").
  let vers = '6';

  try {
    [vers] = (0, _child_process.execSync)('npm -v').toString().trim().split('.');
  } catch (error) {
    console.log(error);
  }

  return vers;
}

function getCWD() {
  // require("child_process").
  let cwd = process.cwd();

  try {
    let ress = (0, _child_process.execSync)('npm bin').toString();
    let i = ress.lastIndexOf('node_modules');
    cwd = i === -1 ? cwd : ress.slice(0, i);
  } catch (error) {
    console.log(error);
  }

  return cwd;
} // experimental argumnet parsing logic


args.forEach(option => {
  if (/^--./.test(option)) {
    let equIndex = option.indexOf('='); // equIndex = equIndex === -1 ? option.length : equIndex;

    let key = option.slice(2, equIndex);
    let value = option.slice(equIndex + 1);

    if (equIndex === -1) {
      key = option.slice(2);
      value = true;
    }

    key = key.replace(/-|:/g, '_');
    processEnv[key] = value;
  }
});

let defaulter = (target, source) => {
  let defaultObject = {};
  Object.keys(target).forEach(key => {
    let data = target[key];

    if (data && typeof data === 'object') {
      if (Array.isArray(data)) {
        defaultObject[key] = source[key] || data;
      } else if (typeof data.cli === 'string') {
        let cliData;

        if (typeof processEnv[data.cli] === 'string') {
          cliData = processEnv[data.cli];
        } else if (typeof processEnv[data.cli.toLowerCase()] === 'string') {
          cliData = processEnv[data.cli.toLowerCase()];
        } else {
          cliData = source && source[key] || data.value;
        }

        if (typeof data.value === 'boolean') {
          cliData = cliData === 'true' || cliData === true ? true : cliData === 'false' || cliData === false || cliData === '' ? false : data.value;
        }

        defaultObject[key] = cliData;
      } else {
        defaultObject[key] = defaulter(data, source && source[key] ? source[key] : Array.isArray(target[key]) ? [] : {});
      }
    } else {
      defaultObject[key] = typeof source === 'object' && source[key] !== null && typeof source[key] !== 'undefined' ? source[key] : target[key];
    }
  });
  return defaultObject;
};

global.reactCLIOptions = null;

const getOptions = () => {
  if (global.reactCLIOptions) {
    return global.reactCLIOptions;
  }

  let appPath = process.cwd();
  let userSchemas;

  let packagePath = _path.default.join(appPath, 'package.json');

  if (_fs.default.existsSync(packagePath)) {
    userSchemas = require(packagePath)['react-cli'] || {};
  }

  let options = defaulter(_defaultConfigValues.default, userSchemas || {}); // for future may be for npm 8 edge cases

  options.npmVersion = getNpmVersion();
  options.cwd = getCWD();
  options.packageVersion = process.env.npm_package_version;
  options.extraArgs = process.argv.slice(3);
  options.commandOption = process.argv[2];
  global.reactCLIOptions = options;
  return options;
};

exports.getOptions = getOptions;