#include "server_tcp_connect.hpp"
#include "abstract_tcp_connect.hpp"
#include "logger.hpp"
#include "tcp_server.hpp"
#include "tinypb_data.hpp"


namespace tinyrpc {
    ServerTcpConnection::ServerTcpConnection(int fd, Reactor& reactor, TcpServer& ser) :
    AbstractTcpConnection(fd, reactor),
    m_server(ser)
    {

    }
    ServerTcpConnection::~ServerTcpConnection() {

    }
    void ServerTcpConnection::process()  {
        while(m_readBuffer.getReadable() > 0) {
            std::shared_ptr<AbstractData> data(new TinypbData);

            bool ret = m_server.getCoder().decoder(m_readBuffer, *data);

            if(ret == false) {
                logger() << "decode error";
                break;
            }
            
            std::unique_ptr<AbstractData> resp(new TinypbData);
            m_server.getDispatcher().dispatcher(*this, *data,  *resp);
            m_server.getCoder().encoder(m_writeBuffer, *resp);
             
        }
    }
}