import { GLShader } from '../../../glCore';
//顶点着色器程序
const VSHADER_SOURCE =
    "precision highp float;" +
    "attribute vec2 aVertexPosition;" +
    "attribute vec2 aTextureCoord;" +
    "attribute vec4 aColor;" +
    "attribute float aTextureId;" +

    "uniform mat3 projectionMatrix;" +
    // "uniform mat3 modelMatrix;" +

    "varying vec2 vTextureCoord;" +
    "varying vec4 vColor;" +
    "varying float vTextureId;" +

    "void main(void){" +
    "gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
    // "gl_Position = vec4((projectionMatrix *modelMatrix* vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);" +
    "vTextureCoord = aTextureCoord;" +
    "vTextureId = aTextureId;" +
    "vColor = aColor;" +
    "}";
//片元着色器程序
const fragTemplate = [
    'precision mediump float;',
    'varying vec2 vTextureCoord;',
    'varying vec4 vColor;',
    'varying float vTextureId;',
    'uniform sampler2D uSamplers[%count%];',

    'void main(void){',
    'vec4 color;',
    'float textureId = floor(vTextureId+0.5);',
    '%forloop%',
    'gl_FragColor = color * vColor;',
    '}',
].join('\n');


/**
 * 创建批处理专用着色器，核心，切换纹理
 * @param gl 
 * @param maxTextures 最大纹理数
 */
export function generateMultiTextureShader(gl, maxTextures) {
    // const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8');
    let fragmentSrc = fragTemplate;

    fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures);
    fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures));
// console.log(fragmentSrc)
    const shader = new GLShader(gl, VSHADER_SOURCE, fragmentSrc);

    const sampleValues = [];

    for (let i = 0; i < maxTextures; i++) {
        sampleValues[i] = i;
    }

    shader.bind();
    shader.uniforms["uSamplers"] = sampleValues;
    // console.log(fragmentSrc)
    return shader;
}

function 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(textureId == ${i}.0)`;
        }

        src += '\n{';
        src += `\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`;
        src += '\n}';
    }

    src += '\n';
    src += '\n';

    return src;
}
