#include "pultwindow_desktop.h"
#include <QMouseEvent>
#include <QApplication>
#include <QMessageBox>
#include <QTimer>
#include "piconfig.h"


PultWindowDesktop::PultWindowDesktop(): PultWindowBase() {
#ifndef ANDROID
	display_on = true;
	sides_count = piMaxi(1, PIConfig("pult.conf", PIIODevice::ReadOnly).getValue("sides_count", 1).toInt());
//	pin_display;// = device_pool.GPIOPinIndex("screen_state");
	if (pin_display == 0) {
		//piCout << "Error: pin \"screen_state\" in \"gpio.conf\" not found!";
	} else {
		///setCursor(Qt::BlankCursor);
	}
//	display_on;// = device_pool.gpio.pinState(pin_display);
	if (!display_on)
		pressScreenButton();
	timer = 0;
	display_control = true;
	timer_mc = startTimer(100);
#endif
}


PultWindowDesktop::~PultWindowDesktop() {
#ifndef ANDROID
	stopTimer();
	killTimer(timer_mc);
#endif
}


#ifndef ANDROID


void PultWindowDesktop::pressScreenButton() {
	if (!display_control) return;
	int pin = 0;//device_pool.GPIOPinIndex("screen");
	if (pin == 0) {
		piCout << "Error: pin \"screen\" in \"gpio.conf\" not found!";
		return;
	}
	//piCout << "set pin" << pin << "1";
	//device_pool.gpio.pinClear(pin);
	piMSleep(200);
	//device_pool.gpio.pinSet(pin);
	//piCout << "set pin" << pin << "0";
	piMSleep(200);
	//display_on = !display_on;
	//display_on = device_pool.gpio.pinState(pin_display);
	if (layout() != 0)
		if (layout()->itemAt(0) != 0)
			if (layout()->itemAt(0)->widget() != 0) {
				if (!display_on)
					layout()->itemAt(0)->widget()->hide();
				else {
					display_control = false;
					QTimer::singleShot(1500, layout()->itemAt(0)->widget(), SLOT(show()));
				}
			}
	stopTimer();
}


void PultWindowDesktop::timerEvent(QTimerEvent * e) {
	if (e->timerId() == timer) {
		//if (display_on) pressScreenButton();
		return;
	}
	if (e->timerId() == timer_mc) {
		//display_on = device_pool.gpio.pinState(pin_display);
		static QPoint pp;
		QPoint cp = QCursor::pos();
		if (pp != cp) {
			restartTimer(30000);
			pp = cp;
		}
		return;
	}
	PultWindowBase::timerEvent(e);
}


void PultWindowDesktop::mousePressEvent(QMouseEvent * e) {
	//qDebug() << e->x() << e->y();
	if (!display_on && e->x() != 0)
		pressScreenButton();
	restartTimer(30000);
	if (e->button() == Qt::NoButton) {
		QWidget::mousePressEvent(e);
		return;
	}
	if (e->x() != 0) {
		QWidget::mousePressEvent(e);
		return;
	}
	float y = e->y() / float(height());
	//qDebug() << y;
	int sn = piFloorf(y * sides_count);
	if (sn == 0) {
		pressScreenButton();
	} else {
		//device_pool.sidePressed(sn);
	}
	QWidget::mousePressEvent(e);
}


#endif
