#version 330 core

in vec3 normal;
in vec3 fragmentPosition;
in vec2 textureCoordinate;

flat in mat3 TBN;


uniform float shininess;

uniform vec4 ambientLight;
uniform vec3 lightPositions[2];
uniform float lightBrightness[2];

uniform vec4 lightColor;

uniform sampler2D textureSampler;

uniform bool useSecondaryTexture;
uniform bool useNormalMap;

uniform sampler2D secondaryTexture;
uniform sampler2D normalMap;


float emissionStrength = 0.0;


void main() {
	vec4 color = vec4(texture(textureSampler, textureCoordinate).rgb, 1.0);

	if (useSecondaryTexture) {
		vec4 secondColor = texture(secondaryTexture, textureCoordinate).rgba;
		color = vec4(color.rgb * (1 - secondColor.a) + secondColor.rgb * secondColor.a, min(color.a + secondColor.a, 1.0));
	}

	vec3 norm;
	vec3 eyeDir = (-normalize(fragmentPosition));
	if (useNormalMap) {
		norm = normalize((texture(normalMap, textureCoordinate).xyz * 2 - vec3(1,1,1)));
		eyeDir = TBN * eyeDir;
	} else {
		norm = normalize(normal);
	}

	float sumDiffusion = 0;
	float sumSpecular = 0;

	for (int i = 0; i < lightPositions.length(); i++) {
		vec3 lightDir = normalize(lightPositions[i] - fragmentPosition);

		if (useNormalMap) {
			lightDir = TBN * lightDir;
		}

		sumDiffusion += max(dot(norm, lightDir), 0.0) * lightBrightness[i];

		vec3 halfway = (lightDir + eyeDir) / length(lightDir + eyeDir);
		sumSpecular += pow(max(dot(halfway, norm), 0.0), shininess);
	}

	gl_FragColor =
		// EMISSION
		color * emissionStrength +

		// // AMBIENT
		ambientLight * color +

		// DIFFUSION
		color * sumDiffusion +

		// SPECULAR
		sumSpecular * lightColor * color;
}