#version 450 core
#extension GL_ARB_shading_language_include : require
#include "../../lib/lights.fs"

//foliage.fs

struct Material {
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
}; 

in vec3 FragPos;
in vec3 ViewFragPos;
in vec3 Normal;
in vec2 TexCoord;
in vec4 FragPosLightSpace;
in vec3 normalRot1;
in vec3 normalRot2;


uniform dvec3 viewPos;
// uniform DirLight dirLight;
// uniform PointLight pointLights[NR_POINT_LIGHTS];
// uniform SpotLight spotLight;
uniform Material material;

//texture stuff
// uniform sampler2D ourTexture;
uniform int hasTransparency;
// uniform sampler2D specularTexture;
uniform vec3 baseColor;
uniform vec3 tipColor;


uniform mat4 view;


/**
The output
*/
out vec4 FragColor;

// function prototypes
float easeIn(float interpolator);
float easeOut(float interpolator);

void main(){

    //basic vars
    float heightPercent = TexCoord.y;

    //calculate color
    vec3 textureColor = mix(baseColor,tipColor,easeIn(heightPercent));

    //mix normals
    float normalMix = TexCoord.x;
    float normalMultiplier = -(1.0 + -2.0 * int(gl_FrontFacing));
    vec3 norm = normalize(mix(normalRot1,normalRot2,normalMix) * normalMultiplier);
    // vec3 norm = normalize(Normal * normalMultiplier);
    vec3 viewDir = normalize(vec3(viewPos) - FragPos);
    
    //grab light intensity
    vec3 lightIntensity = vec3(calcLightIntensityTotal(norm));

    //get color of base texture
    // vec3 textureColor = vec3((norm.x + 1) / 2.0, norm.y, 1.0 - (norm.x + 1) / 2.0);
    // vec3 textureColor =  vec3(TexCoord,1.0);
    // vec3 textureColor = vec3(0.17647,0.4,0.09411);//texture(material.diffuse, TexCoord).rgb;

    //shadow
    float shadow = ShadowCalculation(FragPosLightSpace, normalize(-directLight.direction), norm);

    //
    //point light calculations
    uint clusterIndex = findCluster(ViewFragPos, zNear, zFar);
    uint pointLightCount = clusters[clusterIndex].count;
    for(int i = 0; i < pointLightCount; i++){
        uint pointLightIndex = clusters[clusterIndex].lightIndices[i];
        PointLight pointLight = pointLight[pointLightIndex];
        lightIntensity = lightIntensity + CalcPointLight(pointLight, norm, FragPos, viewDir);
    }
    //error checking on light clusters
    if(pointLightCount > MAX_LIGHTS_PER_CLUSTER){
        FragColor = vec4(1.0f,0.0f,0.0f,1);
        return;
    }

    //calculate final color
    vec3 finalColor = textureColor * lightIntensity;// * max(shadow,0.4);
    // vec3 lightAmount = CalcDirLight(norm, viewDir);
    // for(int i = 0; i < NR_POINT_LIGHTS; i++){
    //    lightAmount += CalcPointLight(i, norm, FragPos, viewDir);
    // }

    //this final calculation is for transparency
    FragColor = vec4(finalColor, 1.0);//texture(ourTexture, TexCoord);//vec4(result, 1.0);
}

float easeIn(float interpolator){
    return interpolator * interpolator;
}

float easeOut(float interpolator){
    return 1 - easeIn(1 - interpolator);
}