'use strict';

var _chalk = require('chalk');

var _chalk2 = _interopRequireDefault(_chalk);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _module = require('module');

var _module2 = _interopRequireDefault(_module);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _knex = require('knex');

var _knex2 = _interopRequireDefault(_knex);

var _generate = require('nanoid/generate');

var _generate2 = _interopRequireDefault(_generate);

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

const IS_DEV = process.env.NODE_ENV !== 'production';

const NPM_CMD = /^win/.test(process.platform) ? 'npm.cmd' : 'npm';

const PRINT_LEVELS = {
  info: _chalk2.default.white,
  warn: _chalk2.default.yellow.bind(_chalk2.default, 'WARN'),
  error: _chalk2.default.red.bind(_chalk2.default, 'ERR'),
  success: _chalk2.default.green.bind(_chalk2.default, 'OK')
};

const print = (level, ...args) => {
  let method = PRINT_LEVELS[level];

  if (!method) {
    args = [level].concat(args);
    method = PRINT_LEVELS.info;
  }

  console.log(_chalk2.default.black.bgWhite('[botpress]'), '\t', method(...args));
};

Object.keys(PRINT_LEVELS).forEach(level => {
  print[level] = (...args) => print(level, ...args);
});

const resolveFromDir = (fromDir, moduleId) => {
  fromDir = _path2.default.resolve(fromDir);
  const fromFile = _path2.default.join(fromDir, 'noop.js');
  try {
    return _module2.default._resolveFilename(moduleId, {
      id: fromFile,
      filename: fromFile,
      paths: _module2.default._nodeModulePaths(fromDir)
    });
  } catch (err) {
    return null;
  }
};

const resolveModuleRootPath = entryPath => {
  let current = _path2.default.dirname(entryPath);
  while (current !== '/') {
    const lookup = _path2.default.join(current, 'package.json');
    if (_fs2.default.existsSync(lookup)) {
      return current;
    }
    current = _path2.default.resolve(_path2.default.join(current, '..'));
  }
  return null;
};

const resolveProjectFile = (file, projectLocation, throwIfNotExist) => {
  const packagePath = _path2.default.resolve(projectLocation || './', file);

  if (!_fs2.default.existsSync(packagePath)) {
    if (throwIfNotExist) {
      throw new Error("Could not find bot's package.json file");
    }
    return null;
  }

  return packagePath;
};

const getDataLocation = (dataDir, projectLocation) => dataDir && _path2.default.isAbsolute(dataDir) ? _path2.default.resolve(dataDir) : _path2.default.resolve(projectLocation, dataDir || 'data');

const getBotpressVersion = () => {
  const botpressPackagePath = _path2.default.join(__dirname, '../package.json');
  const botpressJson = JSON.parse(_fs2.default.readFileSync(botpressPackagePath));
  return botpressJson.version;
};

const collectArgs = (val, memo) => {
  memo.push(val);
  return memo;
};

// https://github.com/tgriesser/knex/issues/1871#issuecomment-273721116
const getInMemoryDb = () => (0, _knex2.default)({
  client: 'sqlite3',
  connection: ':memory:',
  pool: {
    min: 1,
    max: 1,
    disposeTiemout: 360000 * 1000,
    idleTimeoutMillis: 360000 * 1000
  },
  useNullAsDefault: true
});

const safeId = (length = 10) => (0, _generate2.default)('1234567890abcdefghijklmnopqrsuvwxyz', length);

const isBotpressPackage = pkg => {
  const [scope, name] = getPackageName(pkg);
  const isBotpress = scope === 'botpress' || name.startsWith('botpress-');
  return isBotpress;
};

const getModuleShortname = pkg => {
  const [, name] = getPackageName(pkg);
  const withoutPrefix = name.replace(/^botpress-/i, '');
  return withoutPrefix;
};

const getPackageName = pkg => {
  const isScoped = pkg.startsWith('@');

  if (isScoped) {
    const [scope, name] = pkg.match(/^@(.*)\/(.*)/).slice(1);
    return [scope, name];
  } else {
    return [null, pkg];
  }
};

module.exports = {
  print,
  resolveFromDir,
  isDeveloping: IS_DEV,
  resolveModuleRootPath,
  resolveProjectFile,
  getDataLocation,
  npmCmd: NPM_CMD,
  getBotpressVersion,
  collectArgs,
  getInMemoryDb,
  safeId,
  isBotpressPackage,
  getModuleShortname
};
//# sourceMappingURL=util.js.map