#include "ZMQClient.hh"

#include <iostream>

ZMQClient::ZMQClient() :
    cancel( 0 ),
    socket(context, ZMQ_REQ)
{
    addr = "";
}

ZMQClient::~ZMQClient()
{
    socket.disconnect(addr);
    socket.close();
}

void ZMQClient::connect(std::string address){
    addr = address;
    if(address != ""){
        socket.connect(address.c_str());
        int timeout = 0;
        socket.setsockopt( ZMQ_LINGER, timeout );
    }
}

std::string ZMQClient::sendMessageToServer(const void *messageData, int messageLength, bool sendMore){
  zmq::message_t message(messageLength);
  memcpy((void *)message.data(), messageData, messageLength);
  if( !socket.send(message, sendMore ? ZMQ_SNDMORE : 0) )
      return "";
  return sendMore ? "" : receiveMessage();
}

std::string ZMQClient::receiveMessage(){
  // Wait for reply
  zmq::message_t reply;
  int ok;
  do {
      ok = socket.recv(&reply, ZMQ_DONTWAIT);
  } while( ok == 0 && !cancel );
  if( ok < 1 || cancel )
      return "";
  std::string replyMessage = std::string(static_cast<char *>(reply.data()), reply.size());
  return replyMessage;
  /*zmq::message_t reply;
  socket.recv(&reply);
  std::string replyMessage = std::string(static_cast<char *>(reply.data()), reply.size());
  return replyMessage;*/
}

std::string ZMQClient::sendStringToServer(std::string messageStr, bool sendMore){
  return sendMessageToServer(messageStr.c_str(), messageStr.size(), sendMore);
}

std::string ZMQClient::sendStringsToServer(std::vector<std::string> messages, bool sendMore){
  for(int unsigned i = 0; i < messages.size() - 1; i++){
    sendStringToServer(messages[i], true);
  }
  return sendStringToServer(messages.back(), sendMore);
}

/* Veraltet und bringt Server zum absturtz
std::string ZMQClient::sendImageToServer(cv::Mat image, bool sendMore){
  if(!image.isContinuous())
  {
    image = image.clone();
  }
  sendStringsToServer({std::to_string(image.cols), std::to_string(image.rows), "3"}, true);
  return sendMessageToServer(image.data, image.cols * image.rows * 3, sendMore);
}*/

std::string ZMQClient::sendImageToServer(cv::Mat image, bool sendMore){
  if(!image.isContinuous())
  {
    image = image.clone();
  }
  sendStringsToServer({std::to_string(image.cols), std::to_string(image.rows), "3"}, true);
  std::vector<uchar> buff;//buffer for coding
  std::vector<int> param(2);
  param[0] = cv::IMWRITE_JPEG_QUALITY;
  param[1] = 60;//default(95) 0-100
  cv::imencode(".jpg", image, buff, param);
  return sendMessageToServer(buff.data(), buff.size(), sendMore);
  //return sendMessageToServer(image.data, image.cols * image.rows * 3, sendMore);
}
