#include "../../common/buffer.h"
#include "../../common/colors.h"
#include "../shaders.h"
#include "../../parse/parser.h"
#include <stdlib.h>

char *help = 
"options:\n\
   convolve <int blursize>\n";
   
int _init_blur(void **data_ptr, char *input)
{
	void* data = malloc(sizeof(int));
	
	if(assign_int(data, input) == 0)
	{
		free(data);
		return 0;
	}
	
	*data_ptr = (void*)data;
	return 1;
}

void _run_blur(void *data)
{
	int i, x, y;
	color blur_color, temp_color;
	unsigned char *fb, *bb;
	int k_size;
	
	k_size = *(int*)data;

	fb = main_scene->frame_buffer;
	bb = main_scene->back_buffer;
	
	for(y = k_size; y < main_scene->height - k_size; y++)
	{
		for(x = k_size; x < main_scene->width - k_size; x++)
		{
			main_scene->frame_buffer = fb;

			int xx=0;
			for(i = -k_size; i <= k_size; i++)
			{
				get_color(x+i, y, &temp_color);
				add_colors(&blur_color, &temp_color);
				xx++;
			}

			for(i = -k_size; i <= k_size; i++)
			{
				get_color(x, y+i, &temp_color);
				add_colors(&blur_color, &temp_color);
				xx++;
			}

			//normalize
			multiply_color(&blur_color, 1.0/(2*(2*k_size +1)));
			//multiply_color(&blur_color, 1/xx);

			main_scene->frame_buffer = bb;
			set_color(x, y, &blur_color);
			clear_color(&blur_color);
		}
	}

	main_scene->frame_buffer = bb;
	main_scene->back_buffer = fb;
}


void _cleanup_blur(void* data)
{
	free((int*)data);
}


shader_data blur =
{
	"blur",
	"options:\n   blur <int blursize>\n",
	(int (*)(void*, char*))_init_blur,
	(void* (*)(void*))_run_blur,
	(void* (*)(void*))_cleanup_blur,
};

shader_data* get_blur()
{
	return &blur;
}
