#version 430 core
in VertexData {
	vec3 position_world; // Position
	vec3 normal_world; // Normal
	vec2 uv;
} vert;

out vec4 color;

uniform vec3 camera_world;
uniform samplerCube skybox;

uniform vec3 materialCoefficients; // x = ambient, y = diffuse, z = specular 
uniform float specularAlpha;
uniform sampler2D diffuseTexture;

uniform struct DirectionalLight {
	vec3 color;
	vec3 direction;
} dirL;

uniform struct PointLight {
	vec3 color;
	vec3 position;
	vec3 attenuation;
} pointL2;

uniform struct PointLight {
	vec3 color;
	vec3 position;
	vec3 attenuation;
} pointL;

vec3 phong(vec3 n, vec4 reflection, vec3 l, vec3 v, vec3 diffuseC, float diffuseF, vec3 specularC, float specularF, float alpha, bool attenuate, vec3 attenuation) {
	float d = length(l);
	l = normalize(l);
	float att = 1.0;	
	if(attenuate) att = 1.0f / (attenuation.x + d * attenuation.y + d * d * attenuation.z);
	vec3 r = reflect(-l, n);
	return (diffuseF * diffuseC * max(0, dot(n, l)) + specularF * specularC * pow(max(0, dot(r, v)), alpha)) * att + reflection.rgb; 
}

void main() {	
	vec3 n = normalize(vert.normal_world);
	vec3 v = normalize(camera_world - vert.position_world);
	
	vec3 texColor = texture(diffuseTexture, vert.uv).rgb;
	color = vec4(texColor * materialCoefficients.x, 1); // ambient

	vec3 I = normalize(vert.position_world - camera_world);
    vec3 R = reflect(I, n);
    vec4 reflection = vec4(texture(skybox, R).rgb, 1.0) * 0.2;
	
	// add directional light contribution
	color.rgb += phong(n, reflection, -dirL.direction, v, dirL.color * texColor, materialCoefficients.y, dirL.color, materialCoefficients.z, specularAlpha, false, vec3(0));
			
	// add point light contribution
	color.rgb += phong(n, reflection, pointL2.position - vert.position_world, v, pointL2.color * texColor, materialCoefficients.y, pointL2.color, materialCoefficients.z, specularAlpha, true, pointL2.attenuation);
	color.rgb += phong(n, reflection, pointL.position - vert.position_world, v, pointL.color * texColor, materialCoefficients.y, pointL.color, materialCoefficients.z, specularAlpha, true, pointL.attenuation);

}