"use strict";

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

var _crypto = require("crypto");

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

var _checkIsPatternsMatchFilename = require("./checkIsPatternsMatchFilename");

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

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

const defaultSelectorBlob = '[prefix]-[filename]-[local]';

function getSuitableBlob(customizations = [], filename) {
  const custom = customizations.find(({
    enable,
    patterns
  }) => enable && (0, _checkIsPatternsMatchFilename.checkIsPatternsMatchFilename)(patterns, filename));
  return custom && custom.blob || defaultSelectorBlob;
}

var _default = options => {
  const {
    classNameOptions
  } = options.css;
  const {
    classNamePrefix,
    customizations
  } = classNameOptions;
  return (context, localIdentName, localName) => {
    // NOTE:  in build machine we use date as folder path.
    // So every time we create new build there is path will alway different
    // So, in order to minimize 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);

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

    const cleanFileName = fileNameWithoutExt.replace(/-/g, '_').toLowerCase();
    const suitableBlob = getSuitableBlob(customizations, resourcePath);
    return suitableBlob.replaceAll('[local]', localName).replaceAll('[prefix]', classNamePrefix).replaceAll('[filename]', cleanFileName).replaceAll('[hash]', getHash(`${relativePath}-${localName}`, 10));
  };
};

exports.default = _default;