/*
 * Remote Laboratory Serial Console Part
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2014 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include "define.h"
#include "part.h"

#include <tdeaboutdata.h>   //::createAboutData()
#include <tdeaction.h>
#include <tdelocale.h>
#include <tdemessagebox.h>  //::start()
#include <tdeparts/genericfactory.h>
#include <kstatusbar.h>
#include <kstdaction.h>
#include <tqfile.h>        //encodeName()
#include <tqtimer.h>
#include <tqvbox.h>
#include <tqsocket.h>
#include <tqmutex.h>
#include <tqeventloop.h>
#include <tqapplication.h>
#include <tqpushbutton.h>
#include <klineedit.h>
#include <ktextedit.h>
#include <unistd.h>       //access()
#include <stdint.h>
#include <cmath>

#include "layout.h"

#define NETWORK_COMM_TIMEOUT_MS 15000

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

namespace RemoteLab {

typedef KParts::GenericFactory<RemoteLab::SerialConsolePart> Factory;
#define CLIENT_LIBRARY "libremotelab_serialconsole"
K_EXPORT_COMPONENT_FACTORY( libremotelab_serialconsole, RemoteLab::Factory )


SerialConsolePart::SerialConsolePart( TQWidget *parentWidget, const char *widgetName, TQObject *parent, const char *name, const TQStringList& )
	: RemoteInstrumentPart( parent, name ), m_commHandlerState(-1), m_commHandlerMode(0), m_commHandlerCommandState(0), m_connectionActiveAndValid(false), m_base(0)
{
	// Initialize important base class variables
	m_clientLibraryName = CLIENT_LIBRARY;

	// Initialize mutex
	m_instrumentMutex = new TQMutex(false);

	// Initialize kpart
	setInstance(Factory::instance());
	setWidget(new TQVBox(parentWidget, widgetName));

	// Create timers
	m_forcedUpdateTimer = new TQTimer(this);
	connect(m_forcedUpdateTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));
	m_updateTimeoutTimer = new TQTimer(this);
	connect(m_updateTimeoutTimer, SIGNAL(timeout()), this, SLOT(mainEventLoop()));

	// Create widgets
	m_base = new SerialConsoleBase(widget());

	// Initialize widgets
	m_base->setMinimumSize(500,350);

	connect(m_base->sendText, SIGNAL(clicked()), this, SLOT(sendTextClicked()));
	connect(m_base->textInput, SIGNAL(returnPressed()), m_base->sendText, SIGNAL(clicked()));

	TQTimer::singleShot(0, this, TQT_SLOT(postInit()));
}

SerialConsolePart::~SerialConsolePart() {
	if (m_instrumentMutex->locked()) {
		printf("[WARNING] Exiting when data transfer still in progress!\n\r"); fflush(stdout);
	}

	disconnectFromServer();
	delete m_instrumentMutex;
}

void SerialConsolePart::postInit() {
	setUsingFixedSize(false);
}

bool SerialConsolePart::openURL(const KURL &url) {
	int ret;
	m_connectionActiveAndValid = false;
	ret = connectToServer(url.url());
	processLockouts();
	return (ret != 0);
}

bool SerialConsolePart::closeURL() {
	disconnectFromServer();
	m_url = KURL();
	return true;
}

void SerialConsolePart::processLockouts() {
	if (m_connectionActiveAndValid) {
		m_base->setEnabled(true);
	}
	else {
		m_base->setEnabled(false);
	}
}

void SerialConsolePart::disconnectFromServerCallback() {
	m_forcedUpdateTimer->stop();
	m_updateTimeoutTimer->stop();
	m_connectionActiveAndValid = false;
}

void SerialConsolePart::connectionFinishedCallback() {
	connect(m_socket, SIGNAL(readyRead()), m_socket, SLOT(processPendingData()));
	m_socket->processPendingData();
	connect(m_socket, SIGNAL(newDataReceived()), this, SLOT(mainEventLoop()));
	m_tickerState = 0;
	m_commHandlerState = 0;
	m_commHandlerMode = 0;
	m_socket->setDataTimeout(NETWORK_COMM_TIMEOUT_MS);
	m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
	processLockouts();
	mainEventLoop();
	return;
}

void SerialConsolePart::connectionStatusChangedCallback() {
	processLockouts();
}

void SerialConsolePart::setTickerMessage(TQString message) {
	m_connectionActiveAndValid = true;
	TQString tickerChar;
	switch (m_tickerState) {
		case 0:
			tickerChar = "-";
			break;
		case 1:
			tickerChar = "\\";
			break;
		case 2:
			tickerChar = "|";
			break;
		case 3:
			tickerChar = "/";
			break;
	}
	setStatusMessage(message + TQString("... %1").arg(tickerChar));
	m_tickerState++;
	if (m_tickerState > 3) {
		m_tickerState = 0;
	}
}

#define UPDATEDISPLAY_TIMEOUT		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = 2;																\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Server ping timeout.  Please verify the status of your network connection."));						\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define COMMUNICATIONS_FAILED		m_connectionActiveAndValid = false;														\
					m_tickerState = 0;																\
					m_commHandlerState = 2;																\
					m_commHandlerMode = 0;																\
					m_socket->clearIncomingData();															\
					setStatusMessage(i18n("Instrument communication failure.  Please verify the status of your network connection."));				\
					m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);											\
					m_instrumentMutex->unlock();															\
					return;

#define SET_WATCHDOG_TIMER		if (!m_updateTimeoutTimer->isActive()) m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
#define PAT_WATCHDOG_TIMER		m_updateTimeoutTimer->stop(); m_updateTimeoutTimer->start(NETWORK_COMM_TIMEOUT_MS, TRUE);							\
					setTickerMessage(i18n("Connected"));

#define SET_NEXT_STATE(x)		if (m_commHandlerMode == 0) {															\
						m_commHandlerState = x;															\
					}																		\
					else {																		\
						m_commHandlerState = 255;														\
					}

#define EXEC_NEXT_STATE_IMMEDIATELY	m_forcedUpdateTimer->start(0, TRUE);

void SerialConsolePart::mainEventLoop() {
	TQDataStream ds(m_socket);
	ds.setPrintableData(true);

	if (!m_instrumentMutex->tryLock()) {
		EXEC_NEXT_STATE_IMMEDIATELY
		return;
	}

	if (m_socket) {
		if ((m_commHandlerMode == 0) || (m_commHandlerMode == 1)) {
			if (m_commHandlerState == 0) {
				ds << TQString("PING");
				m_socket->writeEndOfFrame();

				m_commHandlerState = 1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			else if (m_commHandlerState == 1) {
				// Receive data
				if (m_socket->canReadFrame()) {
					PAT_WATCHDOG_TIMER

					// Get command status
					TQString input;
					while (!ds.atEnd()) {
						ds >> input;
						if (input == "DATA") {
							TQByteArray data;
							ds >> data;
							TQString textData(data);
							textData.replace("\r", "\n>>>");
							m_base->textOutput->append(">>>" + textData);
						}
					}
					m_socket->clearFrameTail();
					EXEC_NEXT_STATE_IMMEDIATELY
				}
				else {
					if (!m_updateTimeoutTimer->isActive()) {
						UPDATEDISPLAY_TIMEOUT
					}
				}

				// Send data
				if (m_TextToSend != "") {
					TQByteArray data;
					data.duplicate(m_TextToSend.ascii(), strlen(m_TextToSend.ascii()));
					ds << TQString("SEND");
					ds << data;
					m_socket->writeEndOfFrame();

					m_base->textOutput->append("<<<" + m_TextToSend);
					m_TextToSend = "";

					EXEC_NEXT_STATE_IMMEDIATELY
				}
				else {
					ds << TQString("PING");
					m_socket->writeEndOfFrame();
				}
			}
			else if (m_commHandlerState == 2) {
				// Ignore timeouts
				m_commHandlerState = 1;
				EXEC_NEXT_STATE_IMMEDIATELY
			}
			SET_WATCHDOG_TIMER
		}
	}
	else {
		m_commHandlerState = 0;
		m_commHandlerCommandState = 0;
	}

	processLockouts();

	m_instrumentMutex->unlock();
}

void SerialConsolePart::sendTextClicked() {
	m_TextToSend = m_TextToSend + m_base->textInput->text();
	m_base->textInput->setText("");

	// Transmit!
	EXEC_NEXT_STATE_IMMEDIATELY
}

TDEAboutData* SerialConsolePart::createAboutData() {
	return new TDEAboutData( APP_NAME, I18N_NOOP( APP_PRETTYNAME ), APP_VERSION );
}

} //namespace RemoteLab

#include "part.moc"
