#include "net_base.h"

CTcpClient::CTcpClient(asio::io_context& io_context, const std::shared_ptr<spdlog::logger>& logger)
    : logger_(logger), io_context_(io_context), socket_(io_context_)
{
}

CTcpClient::~CTcpClient()
{
}

bool CTcpClient::connect(const std::string& host, const std::string& port)
{
    try {
        asio::ip::tcp::resolver resolver(io_context_);
        asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port);
        asio::connect(socket_, endpoints);
        logger_->info("Connected to {}:{}", host, port);
        return true;
    } catch (const std::exception& ex) {
        logger_->error("Connection failed: {}", ex.what());
        return false;
    }
}

void CTcpClient::disconnect()
{
    if (socket_.is_open()) {
        try {
            socket_.close();
            logger_->info("Disconnected.");
        } catch (const std::exception& ex) {
            logger_->error("Error during disconnection: {}", ex.what());
        }
    }
}

bool CTcpClient::send(const char* data, int len)
{
    try {
        auto send_size = asio::write(socket_, asio::buffer(data, len));
        //logger_->info("Need Send len: {} Real Send len: {}", len, send_size);
        return static_cast<int>(send_size) == len;
    } catch (const std::exception& ex) {
        logger_->error("Send failed: {}", ex.what());
        return false;
    }
}

void CTcpClient::register_func(ExFun_t&& f)
{
    fun_ = f;
}

void CTcpClient::async_recv()
{
    auto self(shared_from_this());
    socket_.async_read_some(asio::buffer(tmp_buf_), [this, self](std::error_code ec, std::size_t length) {
        // logger_->debug("{} {}", __FUNCTION__, ec.message());
        if (ec) {
            if (ec == asio::error::eof) {
                logger_->error("Remote Server Closed.");
                return;
            }
            async_recv();
        } else {
            std::lock_guard<std::mutex> lock(mutex_);
            buffer_.push(tmp_buf_.data(), length);
            auto* frame = CTransProtocal::parse(buffer_);
            if (frame) {
                if (fun_) {
                    fun_(frame);
                }
                delete frame;
            }
            async_recv();
        }
    });
}
