#version 330 core

uniform vec4 vBaseColorValue;
 
uniform sampler2D waterReflection;
uniform sampler2D waterRefraction;
uniform sampler2D normalMap;
uniform sampler2D dudv;

in vec2 texturecoords;
in float time;
in vec4 worldPos;
in vec4 viewSpacePos;

in vec3 viewPosTangient;
in vec3 lightPosTangient;

layout(location = 0) out vec4 fragColor;
 
// Constants //
float kDistortion = 0.015;
float kReflection = 0.01;
vec4 baseColor = vBaseColorValue;

 
void main(void)
{

    vec4 distOffset = texture(dudv, texturecoords + vec2(time)) * kDistortion;
//distOffset = vec4(0,0,0,0);
    vec4 normal = texture(normalMap, vec2(texturecoords + distOffset.xy));
    normal = normalize(normal * 2.0 - 1.0);
   normal.a = 0.81;
normal = vec4(normalize(normal.xyz),0.0);



  vec3 V = normalize(viewPosTangient - worldPos.xyz);

  float w = pow(1.0 - max(0.0, dot(normal.xyz, V)), 5.0);
  vec3 fresnel = mix(baseColor.xyz, vec3(1.0), w);

    // Reflection //
    vec4 dudvColor = texture(dudv, vec2(texturecoords + distOffset.xy));
    dudvColor = normalize(dudvColor * 2.0 - 1.0) * kReflection;
 
    // Projection Coordinates from http://www.bonzaisoftware.com/tnp/gl-water-tutorial/
    vec4 tmp = vec4(1.0 / viewSpacePos.w);
    vec4 projCoord = viewSpacePos * tmp;
    projCoord += vec4(1.0);
    projCoord *= vec4(0.5);
    projCoord += dudvColor;
    projCoord = clamp(projCoord, 0.001, 0.999);
 
    vec4 reflectionColor = mix(texture(waterReflection, projCoord.xy), baseColor, 0.3);
 
    // Refraction //
    vec4 refractionColor = texture(waterRefraction, projCoord.xy);
    vec4 depthValue = vec4(0.1f, 0.1f, 0.1f, 1.0f);
    vec4 invDepth = 1.0 - depthValue;
 
    refractionColor *= invDepth;
    refractionColor += baseColor * depthValue;
 
    fragColor = vec4(fresnel,1) * reflectionColor + (1-vec4(fresnel,1 ))* refractionColor;

//-.-.-.-.-.-.-.-.-.-.-fuer Licht-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
//die lampe braucht noch ambient, difuse und specularkomponente
//material muss auch noch rein

	vec3 n = normalize(normal.xyz);
	vec3 s = normalize( lightPosTangient - worldPos.xyz );
	vec3 v = normalize( - worldPos.xyz );
	vec3 r = reflect( -s, n );
 
	//ambient = Light.La * Material.Ka;
float ambient = 0.1f;
 
	float sDotN = max( dot( s, n ), 0.0 );
	//diffuse = Light[lightIndex].Ld * Material.Kd * sDotN;
vec4 diffuse = fragColor * sDotN;
 
 
	//spec = Light[lightIndex].Ls * Material.Ks * pow( max( dot(r,v) , 0.0 ), Material.Shininess ); 
vec3 spec = vec3(0.9,0.9,0.9)  * pow( max( dot(r,v) , 0.0 ), 2.0 ); 
//fragColor = vec4(spec,1);
//FragColor = vec4( ambientSum + diffuseSum, 1 ) * texColor + vec4( specSum, 1 );
//fragColor = vec4(ambient, ambient, ambient, 1) + diffuse + vec4( spec, 1 );
//-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-

}