var _lastIndexOfInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/last-index-of");

var _spliceInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/splice");

var _startsWithInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/starts-with");

var _indexOfInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/index-of");

const fs = require('fs');

const path = require('path');

const max = require('lodash/max');

const getThemePath = require('../../../utils/cosmic-less-theme');
/**
 * Webpack plugin to rewrite all resolved paths to using THEME path if available
 * @type {CosmicResolve}
 */


module.exports = class CosmicResolve {
  constructor(options) {
    if (!options) options = {};
    this.exts = options.exts || ['less', 'css'];
    this.theme = options.theme;
    this.scope = options.scope;
  }

  apply(compiler) {
    compiler.plugin('normal-module-factory', c => {
      c.plugin('after-resolve', (result, callback) => {
        if (this.shouldProccess(result.rawRequest)) {
          const originalPathArr = result.resource.split(path.sep);

          const lastIndexOfPackages = _lastIndexOfInstanceProperty(originalPathArr).call(originalPathArr, 'packages');

          const lastIndexOfModules = _lastIndexOfInstanceProperty(originalPathArr).call(originalPathArr, 'node_modules');

          const pathRest = _spliceInstanceProperty(originalPathArr).call(originalPathArr, max([lastIndexOfPackages, lastIndexOfModules]) + 1);

          const scope = this.scope;

          if (Boolean(scope) && scope.length) {
            //If scope is given and package is not scoped it might be linked,
            //so we need to change the url to a scoped url
            //because the theme directory expects a scoped path
            if (pathRest[0] !== scope) {
              var _context;

              const linkedScopeName = scope.replace('@', '') + '-';
              const scopePath = scope + '/';

              if (_startsWithInstanceProperty(_context = pathRest[0]).call(_context, linkedScopeName)) {
                pathRest[0] = pathRest[0].replace(linkedScopeName, scopePath);
              }
            }
          }

          const customResolvePath = getThemePath(this.theme);
          const customPath = path.join(customResolvePath, pathRest.join(path.sep)).replace(path.sep + 'src' + path.sep, path.sep);

          if (fs.existsSync(customPath)) {
            result.resource = path.resolve(customPath);
          }
        }

        return callback(null, result);
      });
    });
  }

  shouldProccess(p) {
    return _indexOfInstanceProperty(p).call(p, '.less') > -1;
  }

};