#include "UEUserGuideClient.h"
#include <sstream>
#include <iostream>

#include "Logger/Logger.h"

#include "Processors/TriggerCommandsStrategy.h"

using namespace std;

namespace UpperTestAdapter {
  
namespace Processors {
  
namespace TriggerCommandsGUI {
  
int UEUserGuideClient::SendCommand(boost::shared_ptr<EutIPInterface> eutIface, const std::string &trigger, const std::vector<std::string> &parameterList)
{
  stringstream ss;
  ss << "UEUserGuideClient::SendCommand: " << trigger << " - " << eutIface.get()->Eut() << " - " << eutIface.get()->EutAddress() << " - " << eutIface.get()->EutPort();
  Logger::Instance().LogInfo(ss.str());

  // Encode the request.
  UEUserGuideClientRequest req;
  req.SetTriggerCommand(trigger, parameterList);
  // Place the connection.
  try
  {
    m_client = boost::shared_ptr<SocketClient>(new SocketClient(eutIface.get()->EutAddress(), eutIface.get()->EutPort()));
    // Send message.
    m_client.get()->Send(req.GetEncodedMessage(), req.GetEncodedDataLength());
    // Wait the response.
    char buffer[64] = {0};
    int readBytes = m_client.get()->Receive(64, buffer);
    ss.str("");
    ss << "UEUserGuideClient::SendCommand: received " << readBytes << " bytes";
    Logger::Instance().LogInfo(ss.str());
    // Disconnect.
    m_client.reset();
  // Process the result.
  if (readBytes != 2)
  {
    return -1;
  }
  
    ss.str("");
    ss << "UEUserGuideClient::SendCommand: return " << static_cast<int>((buffer[0] << 4) & 0xf0 | buffer[1] & 0x0f);
    Logger::Instance().LogInfo(ss.str());
    int result = 1;
    switch (static_cast<int>((buffer[0] << 4) & 0xf0 | buffer[1] & 0x0f))
    {
      case TriggerCommandsStrategy::ButtonYes: // Button Yes
      case TriggerCommandsStrategy::ButtonOk: // Button Ok
        result = 0;
        break;
    }
  
    return result;
  }
  catch (string & e)
  {
    Logger::Instance().LogError(e);
    return -1;
  }
}

} } } // namespaces
