#version 130

in vec3 vPosition2;
in vec2 vTexCoords2;
in vec3 vNormal2;

out vec4 outColor;

uniform vec3 diffuseColor;
uniform sampler2D diffuseTextureID;

uniform mat4 viewMatrix;

uniform vec3 light_color;
uniform float light_intensity;
uniform vec3 light_position;
vec3 light_position_viewSpace;


void main() {
  	// Texturing
	vec2 flipped_texcoord = vec2(vTexCoords2.x, 1.0 - vTexCoords2.y);
	vec4 pixelColor = texture2D(diffuseTextureID, flipped_texcoord);

	light_position_viewSpace = (viewMatrix * vec4(light_position, 1)).xyz;

	// Lighting
	vec3 Lp = light_position_viewSpace;
	float Li = light_intensity;
	vec3 Ka = vec3(0.2);
	vec3 Kd = light_color;
	vec3 Ks = vec3(0.6);
	float shininess = 1;
	vec3 n = normalize(vNormal2);
	vec3 s = normalize(vec3(Lp) - vPosition2);
	vec3 v = normalize(vec3(-vPosition2));
	vec3 h = normalize(v + s);
	vec3 pixelLight = vec3(Li * (Ka * pixelColor.rgb) +
			 (Kd * pixelColor.rgb) * max(dot(s, n), 0.0) +
			 (Ks * pixelColor.rgb) * pow(max(dot(h, n), 0.0), shininess));
	
	// Discard fragment if transparent
	if (pixelColor.a < 0.5f)
	{
	    discard;
	}
	
	// Final color
	outColor = vec4(pixelColor.rgb*diffuseColor*pixelLight, pixelColor.a);
	//outColor = vec4((pixelColor.rgb), 1);//*diffuseColor*pixelLight).x, 1, 1, 1);
	//outColor = vec4(1,1,1,1) + vec4(diffuseColor, 1) - vec4(diffuseColor, 1);
}
