#include "touch_butt.h"

touch_butt::touch_butt(int butt_index, QString caption, QColor colr, QColor colg, QColor colw, QColor colp, QPushButton * parent) : QPushButton(parent)
{
	cr = colr; cg = colg; cw = colw; cp = colp;
	aim_col = this->palette().button().color();
	next_col = aim_col;
	index = butt_index;
	this->setText(caption);
	connect(this,SIGNAL(pressed()),SLOT(butt_push()));
	connect(this,SIGNAL(clicked()),SLOT(butt_click()));
	connect(this,SIGNAL(toggled(bool)),SLOT(butt_toggle(bool)));
	connect(this,SIGNAL(released()),SLOT(butt_release()));
	timer = new QTimer(this);
	connect(timer,SIGNAL(timeout()),this,SLOT(timerDone()));
	timer->start(10);
	setWhite();
	is_push = false;
}


void touch_butt::setColor(QColor colr, QColor colg, QColor colw, QColor colp)
{
    cr = colr; cg = colg; cw = colw; cp = colp;
    setWhite();
}


void touch_butt::timerDone()
{
	float r = this->palette().button().color().redF();
	float g = this->palette().button().color().greenF();
	float b = this->palette().button().color().blueF();
	r += (aim_col.redF()-r)/9.0f;
	g += (aim_col.greenF()-g)/9.0f;
	b += (aim_col.blueF()-b)/9.0f;
	QPalette pal;
	pal.setColor(QPalette::Button,QColor(qRound(r*255.0f),qRound(g*255.0f),qRound(b*255.0f)));
	this->setPalette(pal);
	if (qAbs(aim_col.redF() - r) < 0.02 && qAbs(aim_col.greenF() - g) < 0.02 && qAbs(aim_col.blueF() - b) < 0.02)
	{
		pal.setColor(QPalette::Button,aim_col);
		this->setPalette(pal);
		aim_col = next_col;
	}
}


void touch_butt::butt_click()
{
	is_push = false;
	//setWhite();
	//timerDone();
	emit touch_click(index);
}


void touch_butt::butt_push()
{
	is_push = true;
	setPush();
	emit touch_push(index);
}


void touch_butt::butt_release()
{
	is_push = false;
	setWhite();
	timerDone();
}


void touch_butt::butt_toggle(bool checked)
{
	if (!checked) {
		setWhite();
	}
	emit touch_toggle(index,checked);
}


void touch_butt::setRed()
{
	next_col = cr;
	timerDone();
}


void touch_butt::setGreen()
{
	//if (!is_push)
		next_col = cg;
}


void touch_butt::setWhite()
{
	//if (!is_push)
		next_col = cw;
}


void touch_butt::setPush()
{
	next_col = cp;
	timerDone();
}
