#include <stdint.h>
#include <sstream>
#include "threads.h"
#include "socket.h"
#include "socket_stream.h"
#include "logging_thread.h"
#include "motor_interogator.h"

using namespace std;

void* LoggingThread::Run(void* parameter)
{
	try {
		tcp_listener labview(m_LabviewPortNumber);
		labview.listen();
		m_Winch.EchoOff();
		m_LevelWind.EchoOff();
		for(;;)
			logData(labview.accept()); // Wait for someone to connect
	}
	catch (socket_error_ex& e) {
		cout << "Exception: " << e.what() << endl;
		cout << "Err=" << e.whaterr() << endl;
		cout << "Txt=" << e.whatsystext() << endl;
	}
	catch (socket_error& e) {
		cout << "Exception: " << e.what() << endl;
	}
	return 0;
}

void LoggingThread::logData(tcp_socket labviewSocket)
{
	try {
		stringstream responseStream;
		string       response;
		double		 localPeriod;

		labviewSocket.set_input_formatter(new line_input_formatter());
		for (;;) {
			m_ExclusiveAccess.Acquire();
			localPeriod = m_LoggingPeriod;
			m_ExclusiveAccess.Release();
			sleep( localPeriod );
			m_WinchInterogator.Query();
			responseStream << m_WinchInterogator;
			response = responseStream.str();
			labviewSocket.send(response);
			m_LevelWindInterogator.Query();
			responseStream << m_LevelWindInterogator;
			response = responseStream.str();
			labviewSocket.send(response);
			m_Controller.Query();
			responseStream << m_Controller;
			response = responseStream.str();
			labviewSocket.send(response);
		}
	}
	catch (socket_error_ex& e) {
		m_Winch.Stop();
		m_LevelWind.Stop();
		cout << "Exception: " << e.what() << endl;
		cout << "Err=" << e.whaterr() << endl;
		cout << "Txt=" << e.whatsystext() << endl;
	}
	catch (socket_error& e) {
		cout << "Exception: " << e.what() << endl;
	}
}

void LoggingThread::LoggingPeriod(double period)
{
	if (period < 1.0)
		period = 1.0;

	if (period > 20.0)
		period = 20.0;

	m_ExclusiveAccess.Acquire();
	m_LoggingPeriod = period;
	m_ExclusiveAccess.Release();

}
