"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.loaderResolver = loaderResolver;
exports.moduleResolver = moduleResolver;

var _client_packages_group = require("@zohodesk/client_packages_group");

var _constants = require("../../constants");

var _libAlias = require("./common/libAlias");

var _requireLocalOrGlobal = require("../../utils/requireLocalOrGlobal");

var _logger = require("../../../logger");

/* eslint-disable no-use-before-define */
const defaultPackageGroupNpm = '@zohodesk/client_packages_group';

function decideNodeModulesPath(moduleResolvePath) {
  if (typeof moduleResolvePath === 'string' && moduleResolvePath) {
    const resolverPkg = (0, _requireLocalOrGlobal.requireAllPossible)(moduleResolvePath);

    if (resolverPkg.local) {
      (0, _logger.verboseLogger)(`Local '${moduleResolvePath}' package taken as Module Resolver`);
      return resolverPkg.local.nodeModulesPath;
    }

    if (resolverPkg.global) {
      (0, _logger.messageLogger)(`Global '${moduleResolvePath}' package taken as Module Resolver`);
      return resolverPkg.global.nodeModulesPath;
    }

    (0, _logger.errorLogger)(`
        You have given 'resolve.moduleResolvePath' as "${moduleResolvePath}".
        But it seems that file path have some problem;`);
    process.exit(0);
  }

  const globalResolverPkg = (0, _requireLocalOrGlobal.requireGlobal)(defaultPackageGroupNpm);

  if (globalResolverPkg) {
    (0, _logger.messageLogger)(`Global '${defaultPackageGroupNpm}' package taken as Module Resolver`);
    return globalResolverPkg.nodeModulesPath;
  }

  (0, _logger.verboseLogger)(`CBT default '${defaultPackageGroupNpm}' package taken as Module Resolver`);
  return _client_packages_group.nodeModulesPath;
}

function moduleResolver(options) {
  const {
    preferLocalFirst,
    alias,
    defaultAlias,
    moduleResolvePath
  } = options.resolve;
  const nodeModulesPath = decideNodeModulesPath(moduleResolvePath);
  return {
    modules: useAppNodeModulesAsPreferred(preferLocalFirst, [nodeModulesPath, _constants.cliNodeModulesPath].filter(Boolean)),
    alias: { ...(defaultAlias ? _libAlias.libAlias : {}),
      ...(alias || {})
    },
    extensions: ['.ts', '.js', '.json', '.tsx']
  };
}

function loaderResolver(options) {
  const {
    preferLocalFirst
  } = options.resolve;
  return {
    modules: useAppNodeModulesAsPreferred(preferLocalFirst, [_constants.cliNodeModulesPath])
  };
}

function useAppNodeModulesAsPreferred(preferLocalFirst = false, paths = []) {
  const filteredPaths = paths.filter(Boolean);
  return preferLocalFirst ? ['node_modules', ...filteredPaths, _constants.appNodeModules] : [...filteredPaths, 'node_modules', _constants.appNodeModules];
}