"use strict";

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

/**
 * this function will be used for chunk name, chunk hash, contentHash
 * in these, sometime chunk name and chunk id same for some chunkss so below logic has little towek
 * @param {Chunk} chunks
 * @returns { mapExpr, mapExprWithLength }
 */
function templateHashHelpers(chunks) {
  /**
   * @param {function(Chunk): string | number} fn function from chunk to value
   * @returns {string} code with static mapping of results of fn
   */
  const createMap = fn => {
    const obj = {};
    let useId = false;
    let lastKey;
    let entries = 0; // eslint-disable-next-line no-restricted-syntax

    for (const c of chunks) {
      const value = fn(c);

      if (value === c.id) {
        useId = true;
      } else {
        obj[c.id] = value;
        lastKey = c.id;
        entries++;
      }
    }

    if (entries === 0) {
      return 'chunkId';
    }

    if (entries === 1) {
      return useId ? `(chunkId === ${JSON.stringify(lastKey)} ? ${JSON.stringify(obj[lastKey])} : chunkId)` : JSON.stringify(obj[lastKey]);
    }

    return useId ? `(${JSON.stringify(obj)}[chunkId] || chunkId)` : `${JSON.stringify(obj)}[chunkId]`;
  };
  /**
   * @param {function(Chunk): string | number} fn function from chunk to value
   * @returns {string} code with static mapping of results of fn for including in quoted string
   */


  const mapExpr = fn => `" + ${createMap(fn)} + "`;
  /**
   * @param {function(Chunk): string | number} fn function from chunk to value
   * @returns {function(number): string} function which generates code with static mapping of results of fn for including in quoted string for specific length
   */


  const mapExprWithLength = fn => length => // console.log('called with lentch', length),
  `" + ${createMap(c => `${fn(c)}`.slice(0, length))} + "`;

  return {
    mapExpr,
    mapExprWithLength
  };
}
/**
  function mapExpr(fn) {
    const obj = {};
    // eslint-disable-next-line no-restricted-syntax
    for (const c of chunks) {
      obj[c.id] = fn(c);
    }
    return `(${JSON.stringify(obj)})[chunkId]`;
  }
 */