#version 330 core

in vec2 TexCoord;
  
in vec3 Normal;  
in vec3 FragPos;
in vec4 smCoords;
  
uniform vec3 direction;
uniform vec3 lightPos; 
uniform vec3 lightColor;
uniform vec3 objectColor;
uniform vec3 viewPos;
uniform float cutOff;
uniform float cutOff2; 
uniform float visibility;
uniform int pcf;

out vec4 color;
out vec4 shini;

// Texture samplers
uniform sampler2D texture_diffuse1;
uniform sampler2D texture_specular1;
uniform sampler2D shadowMap;

void main(){
	vec3 lightDir = normalize(lightPos - FragPos);



	if(dot(-lightDir,direction)> cutOff){ 

			vec3 norm = normalize(Normal);

	//used for shadow calculation
				vec3 smProj= smCoords.xyz/smCoords.w;	
				float z = texture(shadowMap, smProj.xy).r;
				float shadowMult = z>smProj.z? 1.0:0.0;
				//float shadowMult = 0.0f;//z>smProj.z? 1.0:0.0;
			if(pcf==1){
				float texsiz = 1.0/900.0;
				shadowMult = 0.0;
				for(int x=-2; x<=2; ++x){
					for(int y=-2; y<=2; ++y){
						float pcfDepth = texture(shadowMap, smProj.xy + vec2(x,y)*texsiz).r;
						shadowMult += smProj.z > pcfDepth? 1.0:0.0;
					}
				}
				shadowMult/=25.0f;
				shadowMult  = (1.0 - (shadowMult));
			}
			// vec3 ambient = ____________ * lightColor *0.2f;float shadowMult = (length(max((lightPos.xz- depth_c),(depth_c-lightPos.xz))) < length(max((lightPos.xz- smProj.xz),(smProj.xz-lightPos.xz))))? 0.0:1.0;
		  
			vec3 reflectDir = reflect(lightDir, norm); 

			vec3 viewDir = normalize(viewPos - FragPos);
			float spec =0;
	
			// Linearly interpolate between both textures (second texture is only slightly combined)
			color = texture(texture_diffuse1, TexCoord);
			shini = texture(texture_specular1, TexCoord);
			spec = pow(dot(lightDir,normalize(-direction)),length(shini));  

			float heightAttenuation = smoothstep(10.0f, 0.0f, length(lightDir));
			vec3 specular = spec * lightColor*0.4f*heightAttenuation; 

			if(dot(lightDir,normalize(-direction))<cutOff2){
	
				float cosDir = dot(lightDir, -direction);
				float spotEffect = smoothstep(cutOff, cutOff2, cosDir);
				specular = specular * spotEffect;
		
			}else{
				specular = specular *1.1;
			}

			vec3 result = (specular)*visibility*shadowMult;//*objectColor

			color = shini* color*vec4(result, 1.0f);
		}
}
