#include "tcp_client.hpp"
#include "client_tcp_connect.hpp"
#include "fd_event.hpp"
#include "logger.hpp"
#include "net_address.hpp"
#include "reactor.hpp"
#include "tinypb_coder.hpp"
#include <unistd.h>


namespace tinyrpc {

    TcpClient::TcpClient(const NetAddress& peerAddr) : 
        m_peer_addr(peerAddr),
        m_reactor(*Reactor::getReactor())
        
    {
        m_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (m_fd == -1) {
            logger() << "call socket error, fd=-1, sys error=" << strerror(errno);
        }
        m_local_addr = NetAddress("127.0.0.1", 0);
        m_coder = new TinypbCoder();
        m_connection = new ClientTcpConnection(m_fd, m_reactor, *this);

    }

    TcpClient::~TcpClient() {
        m_reactor.delFdEvent(FdEventPool::getInstance()->getFdEvent(m_fd));
        if(m_fd != -1) close(m_fd);
        delete m_coder;
        delete m_connection;
    }

}