
#include "echo.pb.h"
#include "echo_opcode.h"


using namespace minirpc;
 

class EchoServerMessageHandler : public ServerMessageHandler 
{
 public:
  EchoServerMessageHandler(RpcConnection *connection)
    : ServerMessageHandler(connection) 
  {
  }

  virtual ~EchoServerMessageHandler() 
  {
  }

  bool handlePacket(const MessageHeader &header, Buffer* buffer) override
  {
    if (header.opcode != CMSG_ECHO) 
	  {
      LOG(ERROR) << "opcode error: " << header.opcode;
      return false;
    }
    echo::EchoRequest request;
    if (!buffer->deserializeMessage(&request, header.length)) 
	  {
      LOG(ERROR) << "deserializeMessage error: " << header.length;
      return false;
    }
    LOG(INFO) << "request: " << request.message();
    echo::EchoResponse response;
    response.set_response(request.message());
    connection_->sendPacket(SMSG_ECHO, &response);
    return true;
  }
};

class EchoServerMessageHandlerFactory: public ServerMessageHandlerFactory 
{
 public:
  EchoServerMessageHandlerFactory() 
  {
  }
  virtual ~EchoServerMessageHandlerFactory() 
  {
  }
  ServerMessageHandler* CreateHandler(RpcConnection *connection) 
  {
    return new EchoServerMessageHandler(connection);
  }
};


int main(int argc, char *argv[]) 
{
  ReactorLoop loop;
  EchoServerMessageHandlerFactory *factory=new EchoServerMessageHandlerFactory();
  std::string host="127.0.0.1";
  int port=22202;
  RpcServer server(&loop,host, port,factory);
  loop.startInOtherThread();
  server.start();
  return 0;
}

 
