#version 330

#define MAX_LIGHTS 2
uniform struct Light {
    int flags;
    vec4 position;
    vec4 direction;
    mat4 viewMatrix;
    vec3 colour;
    float ambient;
    sampler2D s_projTexture;
    vec3 projColour;
} u_light[MAX_LIGHTS];

#define LIGHT_FLAG_ENABLED 1
#define LIGHT_FLAG_TEXTURED 2

uniform struct Material {
  int flags;
  vec3 diffuse;
  vec3 specular;
  float specularExp;
} u_material;

#define MATERIAL_FLAG_TEXTURED 2

uniform sampler2D s_texture0;



in vec4 v_colour;
in vec2 v_texCoord;
in vec4 v_light_projTexCoord[MAX_LIGHTS];

out vec4 fragColor;

vec3 applyLight(Light light, vec4 light_projTexCoord) {
    if ((light.flags & LIGHT_FLAG_TEXTURED) != 0) {
        vec2 tc = vec2(light_projTexCoord.x / light_projTexCoord.w, light_projTexCoord.y / light_projTexCoord.w);
        if (light_projTexCoord.w > 0.0 && tc.x > 0.0 && tc.x < 1.0 && tc.y > 0.0 && tc.y < 1.0) {
            vec2 tcr = tc;
            vec2 tcg = tc;
            // tcg.x -= sin(tc.y * 10.0) * 0.002;
            tcg.x -= 0.002;
            vec2 tcb = tc;
            // tcb.x += sin(5.0 + tc.y * 10.0) * 0.002;
            tcb.x += 0.002;
            vec3 c;

            c.r = texture(light.s_projTexture, tcr).r * 0.75 + sin(mod((tc.x - 0.001) * 1500.0, 3.1415926)) * 0.25;
            c.g = texture(light.s_projTexture, tcg).g * 0.75 + sin(mod((tc.x + 0.000) * 1500.0, 3.1415926)) * 0.25;
            c.b = texture(light.s_projTexture, tcb).b * 0.75 + sin(mod((tc.x + 0.001) * 1500.0, 3.1415926)) * 0.25;
            return c * light.projColour;
        }
    }

    return vec3(0);
}

void main() {
    if ((u_material.flags & MATERIAL_FLAG_TEXTURED) != 0) {
        vec4 texel = texture(s_texture0, v_texCoord);
        fragColor = v_colour * (1.0 - texel.a) + texel * texel.a;
    }
    else {
        fragColor = v_colour;
    }

    if ((u_light[0].flags & LIGHT_FLAG_ENABLED) != 0) fragColor.rgb += applyLight(u_light[0], v_light_projTexCoord[0]);
    if ((u_light[1].flags & LIGHT_FLAG_ENABLED) != 0) fragColor.rgb += applyLight(u_light[1], v_light_projTexCoord[1]);
}
