#version 330

// Input vertex attributes (from vertex shader)
in vec3 fragPosition;
in vec2 fragTexCoord;
in vec4 fragColor;
in vec3 fragNormal;

// Input uniform values
uniform sampler2D texture0;
uniform vec4 colDiffuse;

// Output fragment color
out vec4 finalColor;

#define MAX_LIGHTS 32

struct Light {
    int enabled;
    float distanceNear;
    float distanceFar;
    float power;
    vec3 position;
    vec4 color;
};

uniform Light lights[MAX_LIGHTS];
uniform vec4 ambient;


void main()
{
    vec4 texelColor = texture(texture0, fragTexCoord);
    if (texelColor.a == 0.0) discard;
    if (fragColor.b < 1.0) {
    	finalColor = vec4(1.0, 1.0, 1.0, 1.0);
    } else {
        vec3 lightDot = vec3(0.0);
        vec4 tint = colDiffuse * fragColor;
        vec3 normal = normalize(fragNormal);
        
        for (int i = 0; i < MAX_LIGHTS; i++) {
            if (lights[i].enabled == 1) {
                vec3 light = vec3(0.0);

                light = normalize(lights[i].position - fragPosition);

                float dist = distance(lights[i].position, fragPosition);
                
                float power = smoothstep(lights[i].distanceFar, lights[i].distanceNear, dist);
                float NdotL = max(dot(normal, light), 0.0);
                lightDot += lights[i].color.rgb * power * lights[i].power * NdotL;
                // lightDot += lights[i].color.rgb * power * lights[i].power;
         
            }
        }   
        finalColor.rgb = (texelColor.rgb * lightDot);
        // float c1 = smoothstep(5.0, 5.1, fragPosition.x + fragPosition.y + fragPosition.z);
        // float c2 = smoothstep(5.2, 5.1, fragPosition.x + fragPosition.y + fragPosition.z);
        // finalColor.rgb += vec3(1) * c1 * c2;
        // finalColor.rg = gl_FragCoord.xy / 1000.0;
        // finalColor.rgb = normal;  // Kinda testing stuff
        // finalColor = (texelColor * vec4(lightDot, 1.0));
        // finalColor = pow(finalColor, vec4(1.0/2.2));
    }
}
