#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>

#include "RcdWriter.hh"
#include "DuplexSocket.hh"
#include "MpsLaserConfigurationData.hh"

using namespace std;

int main() {
  MpsLaserConfigurationData _cfg;
  
  DuplexSocket *_socket=new DuplexSocket(15000);

    if(_socket==0) {
      std::cerr << "RcdWriterSkt::open()   Error opening socket " << std::endl;
      return 1;
    }

    std::cout << "RcdWriterSkt::open()   Opened socket "
	      << std::endl;


    while(true) {
      char _recvData[37];
      _recvData[36]='\0';

      int n(-1);
      std::cout << "Waiting..."  << std::endl;
      n=_socket->recv(_recvData,36);

      if(n!=36) {
	std::cerr << "Error reading from socket; number of bytes written = "
		  << n << " < 36" << std::endl;
	perror(0);
      }
      
      std::cout << "Recv = " << _recvData << std::endl;

      std::string _sendData;

      // Run data
      if(_recvData[0]=='3') {
	//         123456789012345678901234567890123456
	_sendData="3012345 V01.01.03!!!LOTSOFPADDING!!!";
      }

      // Cfg data write
      if(_recvData[0]=='1') {
	_cfg.parse(std::string(_recvData));
	_sendData="900000000000000000000000000000000000";
	sleep(1);
      }

      // Cfg data read
      if(_recvData[0]=='2') {
	_sendData=_cfg.parse();
	_sendData[0]='2';
      }

      // Trigger
      if(_recvData[0]=='4') {
	_cfg.parse(std::string(_recvData));
	_sendData="900000000000000000000000000000000000";
      }

      std::cout << "Send = " << _sendData << std::endl;

      if(!_socket->send(_sendData.c_str(),36)) {
	std::cerr << "RcdWriterSkt::write()  Error writing to file; number of bytes written < "
		  << 36 << std::endl;
	perror(0);
      }
    }

    delete _socket;
}
