'use strict';

require('../../math/const.js');
require('../../math/groupD8.js');
var Matrix = require('../../math/Matrix.js');
require('../../math/Transform.js');
var Program = require('../shader/Program.js');
var Shader = require('../shader/Shader.js');
var UniformGroup = require('../shader/UniformGroup.js');

class BatchShaderGenerator {
  /**
   * @param vertexSrc - Vertex shader
   * @param fragTemplate - Fragment shader template
   */
  constructor(vertexSrc, fragTemplate) {
    this.vertexSrc = vertexSrc;
    this.fragTemplate = fragTemplate;
    this.programCache = {};
    this.defaultGroupCache = {};
    if (!fragTemplate.includes("%count%")) {
      throw new Error('Fragment template must contain "%count%".');
    }
    if (!fragTemplate.includes("%forloop%")) {
      throw new Error('Fragment template must contain "%forloop%".');
    }
  }
  generateShader(maxTextures) {
    if (!this.programCache[maxTextures]) {
      const sampleValues = new Int32Array(maxTextures);
      for (let i = 0; i < maxTextures; i++) {
        sampleValues[i] = i;
      }
      this.defaultGroupCache[maxTextures] = UniformGroup.UniformGroup.from({ uSamplers: sampleValues }, true);
      let fragmentSrc = this.fragTemplate;
      fragmentSrc = fragmentSrc.replace(/%count%/gi, `${maxTextures}`);
      fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures));
      this.programCache[maxTextures] = new Program.Program({ vertex: this.vertexSrc, fragment: fragmentSrc });
    }
    const uniforms = {
      tint: new Float32Array([1, 1, 1, 1]),
      translationMatrix: new Matrix.Matrix(),
      default: this.defaultGroupCache[maxTextures]
    };
    return new Shader.Shader(this.programCache[maxTextures], uniforms);
  }
  generateSampleSrc(maxTextures) {
    let src = "";
    src += "\n";
    src += "\n";
    for (let i = 0; i < maxTextures; i++) {
      if (i > 0) {
        src += "\nelse ";
      }
      if (i < maxTextures - 1) {
        src += `if(vTextureId < ${i}.5)`;
      }
      src += "\n{";
      src += `
	color = texture2D(uSamplers[${i}], vTextureCoord);`;
      src += "\n}";
    }
    src += "\n";
    src += "\n";
    return src;
  }
}

exports.BatchShaderGenerator = BatchShaderGenerator;
//# sourceMappingURL=BatchShaderGenerator.js.map
