#version 330 core

// Interpolated values from the vertex shaders
in vec2 UV;

// Ouput data
layout(location = 0) out vec3 color;
//out vec3 color;

// Values that stay constant for the whole mesh.
uniform sampler2D foreground;

// Relative width/height of a pixel
uniform float pixWidth;
uniform float pixHeight;


// Pixel state
int IS_BACKGROUND = 0;
int IS_UNDEFINED = 1;
int IS_FOREGROUND = 2;
int UNSET = -1;

vec3 greenValue = vec3(0.0f, 1.0f, 0.0f);
vec3 difference = vec3(40.0f/255.0f);
int radius = 3;


vec3 getColor(vec2 uvCoord) {
    return texture(foreground, uvCoord).rgb;
}

bool isBackground(vec3 c) {
    if (all(   lessThanEqual(c, greenValue+difference)) &&
        all(greaterThanEqual(c, greenValue-difference))
        ) {
        return true;
    } else {
        return false;
    }
}

void main(){
    int status = UNSET;

    for(int w=-radius;w<=radius;w++){
        for(int h=-radius;h<=radius;h++){
            if (w+h==-radius*2) { // first pixel
                if (isBackground(getColor(UV+vec2(pixWidth*w, pixHeight*h)))) {
                    status = IS_BACKGROUND;
                } else {
                    status = IS_FOREGROUND;
                }
            } else { // other pixels
                if (isBackground(getColor(UV+vec2(pixWidth*w, pixHeight*h)))) {
                    if (status != IS_BACKGROUND) {
                        status = IS_UNDEFINED;
                        w=100000;
                        break;
                    }
                } else {
                    if (status != IS_FOREGROUND) {
                        status = IS_UNDEFINED;
                        w=100000;
                        break;
                    }
                }
            }
        }
    }

    if (status == IS_BACKGROUND) {
        color = vec3(0.0f); // black
    } else if (status == IS_FOREGROUND) {
        color = vec3(1.0f); // white
    } else {
        color = vec3(0.5f); // gray
    }
}
