#include "touchbutton.h"


TouchButton::TouchButton(QWidget * parent): QToolButton(parent) {
	init();
}


TouchButton::TouchButton(int id__, const QString & text): QToolButton(0) {
	init();
	id_click = id_yes = id_no = id__;
	setText(text);
}


TouchButton::~TouchButton() {}


void TouchButton::init() {
	connect(this, SIGNAL(clicked(bool)), this, SLOT(_clicked()));
	connect(this, SIGNAL(toggled(bool)), this, SLOT(_toggled(bool)));
	animation.setTargetObject(this);
	animation.setPropertyName("currentColor");
	animation.setEasingCurve(QEasingCurve::OutSine);
	animation.setDuration(350);
	delay_blink = 500;
	anim = auto_gray = true;
	state_           = Gray;
	id_click = id_yes = id_no = -1;
	timer                     = 0;
	pal                       = palette();
	col_yes                   = QColor(Qt::green);
	col_no                    = QColor(Qt::red);
	col_down                  = QColor(Qt::yellow);
	col_gray = col_cur = col_up = pal.button().color();
	col_dst                     = col_gray;
}


void TouchButton::timerEvent(QTimerEvent * e) {
	if (e->timerId() == timer) {
		killTimer(e->timerId());
		timer = 0;
		setCurrentColor(col_blink);
		animateColor(col_dst);
		return;
	}
	QToolButton::timerEvent(e);
}


void TouchButton::mousePressEvent(QMouseEvent * e) {
	animateColor(col_down);
	QToolButton::mousePressEvent(e);
	emit pressedID(id_click);
}


void TouchButton::mouseReleaseEvent(QMouseEvent * e) {
	setCurrentColor(col_down);
	animateColor(col_dst);
	QToolButton::mouseReleaseEvent(e);
	emit releasedID(id_click);
}


void TouchButton::animateColor(const QColor & tc) {
	if (anim) {
		animation.stop();
		animation.setStartValue(currentColor());
		animation.setEndValue(tc);
		animation.start();
	} else {
		col_cur = tc;
		applyColor();
	}
}


void TouchButton::applyState(State s) {
	if (s == state_) return;
	State ps = state_;
	state_   = s;
	emit stateChanged(state_, ps);
	emit stateChangedID(id_click, state_, ps);
}


void TouchButton::blink(const QColor & tc) {
	col_blink = tc;
	if (timer > 0) killTimer(timer);
	timer = startTimer(delay_blink);
}


void TouchButton::setState(State s) {
	switch (s) {
	case Gray: setStateGray(); break;
	case Yes: setStateYes(); break;
	case No: setStateNo(); break;
	default: break;
	};
}
