#version 330 core

in vec3 worldNormal;
in vec3 worldPosition;
in vec2 fragmentUV;

layout(location=0) out vec4 outColor;

uniform sampler2D textureSampler;
uniform vec3 viewVector;
uniform vec3 worldCameraPosition;

#define MAX_LIGHTS 10
uniform struct Light
{
	vec3 position;
	vec3 intensity;
	float attenuation;
} lights[2];

uniform struct Material
{
	vec3 ambientMaterial;
	vec3 diffuseMaterial;
	vec3 specularMaterial;
} material;

vec3 addLightSource(Light light, vec3 textureColor, vec3 worldPosition, vec3 worldCameraPosition, vec3 n, vec3 ambientColor)
{
	//Calculate intensity based on Blinn model
	//light and camera direction
	vec3 viewVector = normalize(worldCameraPosition - worldPosition);
	vec3 lightDirection = normalize(light.position - worldPosition);

	//calculate dot product and get angle
	//clamp result to make sure we don't have negative colors
	float nDotL = clamp(dot(n, lightDirection), 0, 1);
	vec3 diffuseComponent = material.diffuseMaterial * textureColor * light.intensity * nDotL;

	float specularCoeff = 0.0;
	if(nDotL > 0.0)
        specularCoeff = pow(clamp(dot(viewVector, reflect(-lightDirection, n)), 0, 1), 20);

	vec3 specularComponent = material.specularMaterial * specularCoeff * light.intensity;

	//attenuation
    float lightToPosition = length(light.position - worldPosition);
    float attenuation = 1.0 / (1.0 + light.attenuation * pow(lightToPosition, 2));

	return ambientColor + attenuation * (diffuseComponent + specularComponent);
}

void main()
{
	vec3 textureColor = texture(textureSampler, fragmentUV).rgb;
	vec3 ambientColor = material.ambientMaterial * textureColor;

	vec3 colorSum = vec3(0);
	//normalize world normal to get the angle from the dot product
	vec3 n = normalize(worldNormal);

	for(int i=0; i<lights.length(); i++)
	{
		colorSum += addLightSource(lights[i], textureColor, worldPosition, worldCameraPosition, n, ambientColor);
	}
	outColor = vec4(colorSum, 1.0);
	//outColor = vec4(ambientColor + attenuation * (diffuseComponent + specularComponent), 1.0);
}