#include "Consumer.hxx"
#include "../ray/Ray.hxx"
#include <iostream>

Mutex Consumer::mtx;

void Consumer::consume(size_t num_items) {
	if (!pool) {
		return;
	}

	if (num_items <= 0) {
		return;
	}

	this->num_items = num_items;

	start();
}

void Consumer::run() {
	if (!pool) {
		return;
	}

	mtx.lock();
	for(std::vector<std::pair<unsigned int, unsigned int> > vec = pool->pop(num_items);
	vec.size()>0;
	vec = pool->pop(num_items)) {

		for(unsigned int i=0; i<vec.size(); ++i) {
			std::pair<unsigned int, unsigned int> item = vec[i];

			// primary ray to trace
			Ray ray;
			unsigned int x = item.first;
			unsigned int y = item.second;
			Vec3f c = Vec3f(0);

			if(stereo) { 
				Vec3f red;
				Vec3f green;

				camera->InitRay(x, y, ray, -eyedistance);
				red  = Min(Max(scene->RayTrace(ray),Vec3f(0)),Vec3f(1));

				camera->InitRay(x, y, ray, eyedistance);
				green = Min(Max(scene->RayTrace(ray),Vec3f(0)),Vec3f(1));

				c = Vec3f((red.x() + red.y() + red.z()) / 3.0f, (green.x() + green.y() + green.z()) / 3.0f, 0.0f);
			} else {
				camera->InitRay(x, y, ray);

				c = Min(Max(scene->RayTrace(ray),Vec3f(0)),Vec3f(1));
			}

			image[y * camera->resX + x] = c;
		}
	}
	mtx.unlock();
}