#version 120

varying vec3  vertex;
varying vec3  normal;
varying vec3  lightDirection;

uniform vec3  lightColor;
uniform vec3  lightPosition;
uniform vec3  materialColor;
uniform int   materialKind;
uniform int   materialSeed;

uniform int   explLightsNum;
uniform vec3  explLightsPos[10];
uniform float explLightsIntensities[10];

void main()
{
  vec3 Eye       = normalize(-vertex);
  vec3 Reflected = normalize(reflect( -lightPosition, normal));

  vec3 IAmbient  = vec3(0.05f);

  if (materialKind == 6) {
      // sun: shines by itself
      gl_FragColor = vec4(materialColor, 1.0);
      return;
  }

    // TODO: add noise texture
  vec3 color = materialColor;
  color = max(vec3(0.0), min(vec3(1.0), color));

  vec3 light = lightColor * max(dot(normal, lightDirection), 0.0);
  //vec3 light = vec3(0.0);

  int i;
  for (i=0; i<explLightsNum; i++) {
    vec3 explLightColor = vec3(1.0, 0.5, 0.2);
    vec3 diff = vertex - explLightsPos[i];
    float l = 10.0*length(diff);
    float dir = max(0.0, -dot(normal, diff));
    float dp = max(0.0, 1.0-l);

    float intensity = 10.0;
    if (dp == 0.0) {
        intensity *= dir;
    } else {
        intensity *= dp;
    }
    intensity /= 1.0 + 0.5*l*l;

    light += intensity * pow(explLightsIntensities[i], 2.0) * explLightColor;
  }

  light = max(vec3(0.0), light);

  vec3 IDiffuse  = vec3(color) * light;

  // TODO make instensity/exponent as parameter
  //vec3 ISpecular = lightColor * 5.0 * pow(max(dot(Reflected, Eye), 0.0), 2.0);
  //vec3 ISpecular = lightColor * pow(max(dot(Reflected, Eye), 0.0), 2.0);

  //gl_FragColor   = vec4((IAmbient + IDiffuse) + ISpecular, 1.0);
  gl_FragColor   = vec4((IAmbient + IDiffuse), 1.0);
}