"use strict";

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

var _crypto = require("crypto");

var _os = _interopRequireDefault(require("os"));

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

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

function getHash(str) {
  return (0, _crypto.createHash)('md5').update(str).digest();
}

const isWindows = _os.default.platform().toLowerCase() === 'win32';

const isFileEligibleToHashClass = (resourcePath, machineBasedPatterns) => {
  if (!resourcePath.includes('node_modules')) {
    return false;
  }

  return machineBasedPatterns.some(p => resourcePath.includes(p));
};

var _default = options => {
  const {
    classNameOptions
  } = options.css;
  const {
    cssHashSelectors,
    classNamePrefix
  } = classNameOptions;
  let canApplyHashClassName = null;

  if (cssHashSelectors) {
    const {
      filenames,
      packages
    } = cssHashSelectors;
    const machineBasedPatterns = isWindows ? packages.map(e => e.replace(/\//g, '\\')) : packages;

    canApplyHashClassName = function canApplyHashClassName(resourcePath, cleanFileName) {
      return isFileEligibleToHashClass(resourcePath, machineBasedPatterns) || filenames.indexOf(cleanFileName);
    };
  }

  return (context, localIdentName, localName) => {
    // NOTE:  in build macine we use date as folder path.
    // So every time we create new build there is path will alway different
    // in order to minmaze that problem we try in relative path;
    // console.log('context.resourcePath', context.resourcePath, context);
    // let contextResourcePath = context.resourcePath;
    const {
      rootContext,
      resourcePath
    } = context;

    const relativePath = _path.default.relative(rootContext, resourcePath);

    if (resourcePath.endsWith('.plain.css')) {
      return localName;
    }

    const fileNameWithoutExt = _path.default.parse(relativePath).name;

    const cleanFileName = fileNameWithoutExt.replace(/-/g, '_').toLowerCase(); // css file has casesensitive selector issue so can't toLowerCase
    // let local = localName.toLowerCase()

    if (canApplyHashClassName && canApplyHashClassName(resourcePath, cleanFileName)) {
      const h = getHash(`${relativePath}-${localName}`, 10);
      return `${classNamePrefix}${h}`;
    }

    return `${classNamePrefix}-${cleanFileName}-${localName}`;
  };
};

exports.default = _default;