#version 330 core

in vec2 texCoord;
in vec3 N;
in vec3 P;
in vec4 ShadowCoord;
in vec4 LightSpacePos;
in vec3 Normal0;
in vec3 Tangent0;
in float hasTangent;

out vec4 color; 

uniform vec3 light;
uniform vec3 shadowLightDir;
uniform sampler2D color_texture;
uniform sampler2D normal_texture;
uniform sampler2D shadowmap;

uniform vec3 cameraPos;

float getFactor(vec3 suv){
	float xOffset = 1.0/1024.0;
    float yOffset = 1.0/1024.0;
	
	vec2 suvBig = suv.xy * 1024;
	
	vec2 delta = suvBig - round(suvBig);
	

    float factor = 0.0;
	
	float x = 1/81.0;
	
	for (int y = -4 ; y <= 4 ; y++) {
        for (int x = -4 ; x <= 4 ; x++) {
            vec2 Offsets = vec2(x * xOffset, y * yOffset);
            vec3 UVC = vec3(suv.xy + Offsets, suv.z);
			if ( texture( shadowmap, UVC.xy).r  <  UVC.z - 0.0001){
				factor += 0.0;
			} else {
				factor += 1.0;
			}
        }
    }

    return factor*x;
}

vec3 CalcBumpedNormal()
{
    vec3 Normal = normalize(Normal0);
    vec3 Tangent = normalize(Tangent0);
    Tangent = normalize(Tangent - dot(Tangent, Normal) * Normal);
    vec3 Bitangent = -cross(Tangent, Normal);
    vec3 BumpMapNormal = texture(normal_texture, texCoord).xyz;
    BumpMapNormal = 2.0 * BumpMapNormal - vec3(1.0, 1.0, 1.0);
    vec3 NewNormal;
    mat3 TBN = mat3(Tangent, Bitangent, Normal);
    NewNormal = TBN * BumpMapNormal;
    NewNormal = normalize(NewNormal);
    return NewNormal;
}

void main(){
	
	vec3 normal = CalcBumpedNormal();
	
	vec3 suv = ShadowCoord.xyz*0.5 + vec3(0.5, 0.5, 0.5);

	float visibility = getFactor(suv);	
    
    vec3 textureColor = texture(color_texture, texCoord).rgb;
	
	
	//---PointLight
	
    vec3 ray = light-P;
    vec3 lightDirection = normalize(ray);

    float attenuation = 60/length(ray);

    float diffuse = max(0.0, dot(normal,lightDirection));
    
    attenuation = log(attenuation)/2;
    
    if(attenuation < 0){
        attenuation = 0;
    }
    attenuation = sqrt(attenuation);
	
	//--directionalLight
	
	vec3 lightDirection1 = normalize(shadowLightDir);
	
	float attenuation1 = 1.5;
	float diffuse1 = max(0.0, dot(normal,lightDirection1));
	
	float baseLight = 0.3;
		
	//float brightness = baseLight + (1-baseLight)*(attenuation*diffuse + attenuation1*diffuse1*visibility);
	
	float brightness = baseLight + (1-baseLight) * (attenuation*diffuse + attenuation1*diffuse1*visibility);
	
	//float diffuse = max(0.0, dot(normal, lightDirection));	
	//textureColor = vec3(1,1,1);
    //color = vec4(((diffuse*(attenuation*0.7)+0.3f)*textureColor*visibility), 1.0);
	color = vec4(brightness*textureColor, 1);
	
}