#version 400 core
uniform vec3 Kd;
uniform vec3 Ks;
uniform float Kn;

uniform vec3 lDirection;
uniform bool isPhong;
uniform vec3 pointLight[3];
uniform vec4 pointLightCol[3];
uniform mat3 normalMatrix;
uniform float alpha;

in vec3 fNormal;
in vec3 fPosition;

out vec4 fColor;


vec4 calcDirLight(vec4 tex, vec3 fPos, vec3 fNorm, vec3 lightDir) {
        // Get lighting vectors
        vec3 LightDirection = normalize(lightDir);
        vec3 nviewDirection = normalize(fPos);
        vec3 nfNormal = normalize(fNorm);

        // Compute diffuse component
        float diff = max(0.0, dot(nfNormal, -LightDirection));
        vec3 diffV = diff * Kd;

        // Compute specular component
        vec3 Rl = reflect(LightDirection, nfNormal);
        float spec = pow(max(0.0, dot(/*normalMatrix */ Rl, nviewDirection)), Kn);
        vec3 specV = spec * Ks;

        vec3 totalLight = diffV + specV;
        //return vec4(Kd + Ks, 1)
        return vec4(totalLight, alpha);
}

vec4 calcPointLight(vec4 tex, vec3 fPos, vec3 fNorm, int i) {
    // Get lighting vectors
        vec3 LightDirection = normalize(pointLight[i] + fPos);
        vec3 nfNormal = normalize(fNorm);
        vec3 nviewDirection = normalize(fPos);

    // Attenuation
        float distance    = length(nviewDirection - pointLight[i] - fPos) / 3;
        float attenuation = 0.5 + 1 / max(0.25, distance * distance);

    // Compute diffuse component
        float diff = max(0.0, dot(nfNormal, LightDirection));
        vec3 diffV = diff * Kd;

    // Compute specular component
        vec3 Rl = reflect(-LightDirection, /*normalMatrix */ nfNormal);
        float spec = pow(max(0.0, dot(Rl, nviewDirection)), Kn);
        vec3 specV = spec * Ks;

    // Compute ambient component
        vec3 totalLight = attenuation * (diffV + specV);
        return vec4(totalLight, alpha);
}

void
main()
{
    vec4 texColor = vec4(1, 1, 1, alpha);

    // Get lighting vectors
    vec3 LightDirection = normalize(lDirection);
    vec3 nfNormal = normalize(fNormal);
    vec3 nviewDirection = normalize(fPosition);

    fColor = 0.3 * calcDirLight(texColor, fPosition, fNormal, lDirection)
            + 0.4 * calcDirLight(texColor, fPosition, fNormal, vec3(-0.2)-fPosition)
            + 0.1 * calcPointLight(texColor, fPosition, fNormal, 0)/4
            + 0.1 * calcPointLight(texColor, fPosition, fNormal, 1)/4
            + 0.1 * calcPointLight(texColor, fPosition, fNormal, 2)/4
            + 0.14 * vec4(Kd, 1);
    fColor.a = alpha;
}
