"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.cssUrlReplacer = void 0;
Object.defineProperty(exports, "getFileType", {
  enumerable: true,
  get: function () {
    return _getFileType.getFileType;
  }
});
exports.getUrls = void 0;

var _fs = _interopRequireDefault(require("fs"));

var _crypto = _interopRequireDefault(require("crypto"));

var _getFileType = require("./getFileType");

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

const urlRegex = /url\(.*?\)/g;

const getHash = (file, isPath = false, needSubStr = true) => {
  let hash = _crypto.default.createHash('md5');

  if (isPath) {
    hash.update(_fs.default.readFileSync(file));
  } else {
    hash.update(file);
  }

  hash = hash.digest('hex');
  return hash ? needSubStr ? hash.substring(0, 20) : hash : null;
};

const formatUrl = str => {
  let char = str.includes('"') ? '"' : str.includes('\'') ? '\'' : '(';
  const statingIdx = str.indexOf(char) + 1;
  const substr = str.substring(statingIdx, str.length);
  char = char === '(' ? ')' : char;
  return substr.substring(0, substr.indexOf(char));
};

const getUrls = css => {
  const urlMatches = css.match(urlRegex);
  let src = css;

  if (urlMatches) {
    const patterns = {};
    urlMatches.forEach(pattern => {
      const url = formatUrl(pattern);
      const hash = getHash(url);
      patterns[url] = hash;
      const regex = new RegExp(pattern.replace(/([<>*()?${}|])/g, '\\$1'), 'g');
      src = src.replace(regex, hash);
    });
    return {
      urls: patterns,
      css: src
    };
  }
};

exports.getUrls = getUrls;

const cssUrlReplacer = (css, domains, chunkHash = {}) => {
  const obj = getUrls(css);
  let src = css;

  if (obj) {
    const patterns = obj.urls;
    src = obj.css;
    Object.keys(patterns).forEach(pattern => {
      let urlParts = pattern.split('/');
      let fileName = urlParts.pop();

      if (fileName.includes('#')) {
        if (fileName.includes('?')) {
          fileName = fileName.replace(/\?.*#/g, '#');
        }
      } else {
        fileName = fileName.replace(/\?.*$/g, '');
      }

      const hash = patterns[pattern];
      const filename = fileName.replace(/(\?|#).*?$/g, '');
      const regex = new RegExp(hash, 'g');
      let {
        hashedName
      } = chunkHash[filename] || fileName;

      if (domains && typeof urlParts[0] === 'string' && !urlParts[0].includes('http')) {
        const {
          font,
          image
        } = domains;
        const type = (0, _getFileType.getFileType)(filename);
        const customPath = type === 'image' ? `${image}/images` : type === 'font' ? `${font}/fonts` : urlParts.join('/');
        urlParts = customPath.split('/');
      }

      if (hashedName) {
        if (fileName.includes('#')) {
          if (fileName.includes('?')) {
            hashedName = `${hashedName}?${fileName.split('?')[1]}`;
          } else {
            hashedName = `${hashedName}#${fileName.split('#')[1]}`;
          }
        }
      }

      urlParts.push(hashedName || fileName);
      urlParts = urlParts.join('/');
      src = src.replace(regex, `url('${urlParts}')`);
    });
  }

  return src;
};

exports.cssUrlReplacer = cssUrlReplacer;