#include "workspace.h"

#include <qpainter.h>
#include <qpixmap.h>
#include <qimage.h>

#include <math.h>
#include <stdlib.h>
#include <time.h>

#ifndef PI
#define PI 3.1415926535
#endif

Workspace::Workspace(QWidget *parent, const char *name)
: QWidget(parent, name)
{
	degree = 0.1;
	factor = 0.0;
	srand(time(NULL));
	for(int i = 0; i < 4; i++)
	{
		quests[i][0] = 0;
		quests[i][1] = rand() % 2;
		positions[i][0] = 0;
		positions[i][1] = 0;
	}
	startTimer(50);
}

Workspace::~Workspace()
{
}

void Workspace::mousePressEvent(QMouseEvent *e)
{
	if(e->button() == RightButton)
	{
		degree = 0.1;
		factor = 1.2;
	}
	else if(e->button() == LeftButton)
	{
		int number = 0;
		for(int i = 0; i < 4; i++)
			if(quests[i][0]) number++;
		if(number >= 2) return;

		for(int i = 0; i < 4; i++)
			if((abs(e->x() - positions[i][0]) < 30) && (abs(e->y() - positions[i][1]) < 30))
			{
				if(quests[i][0])
				{
					quests[i][1] = !quests[i][1];
					repaint();
					break;
				}
				else if(number <= 2)
				{
					quests[i][0] = 1;
					repaint();
					break;
				}
			}
	}
}

void Workspace::paintEvent(QPaintEvent *e)
{
	QPainter p;
	QPixmap pix("bottle.png");
	QPixmap pix2("quest.png");
	QPixmap pix3;

	QImage im = pix.convertToImage();
	QImage im2 = im.mirror(true, true);
	pix3.convertFromImage(im2);
	
	p.begin(this);

	p.setBrush(QColor(0, 0, 100));
	p.drawEllipse(20, 20, width() - 40, height() - 40);

	float j = degree;
	for(int i = 0; i < 4; i++, j += PI * 2.0 / 4.0)
	{
		positions[i][0] = (int)(sin(j) * width() / 2.4 + width() / 2 - pix.width() / 2);
		positions[i][1] = (int)(cos(j) * height() / 3.4 + height() / 2) - 50;
		p.drawPixmap(QPoint(positions[i][0], positions[i][1]), (!quests[i][0] ? pix2 : (quests[i][1] ? pix : pix3)));
	}

	p.end();
}

void Workspace::timerEvent(QTimerEvent *e)
{
	if(factor != 0.0)
	{
		degree *= factor;
		repaint();
		if(degree > 1000.0)
		{
			factor = 0.0;
			//degree = 0.0;
		}
	}
}

