#include "client.h"
#include <iostream>
#include <of_str.h>

using namespace ofen;
CClient::CClient(const std::shared_ptr<spdlog::logger>& logger) : logger_(logger)
{
    client_ = std::make_shared<CTcpClient>(io_context_, logger_);
    supported_.push_back("GetTaskList");
}

CClient::~CClient()
{
}

void CClient::run()
{
    if (!client_->connect("127.0.0.1", "8080")) {
        logger_->info("{} connect err.", __FUNCTION__);
        return;
    }
    client_->register_func([&](CFrameBuffer* buf) { handle_data(buf); });
    client_->async_recv();
    std::thread thread([&]() { io_context_.run(); });
    char line[512]{};
    while (std::cin.getline(line, 512)) {
        std::string cmd_input(line);
        if (std::strstr(line, "end")) {
            break;
        }
        auto vec = COfStr::split(cmd_input, " ");
        if (vec.size() < 2) {
            logger_->error("input's invalid format.");
            continue;
        }
        auto cmd = vec[0];
        if (cmd == "GetTaskList") {
            bool ret = get_task_list();
            logger_->info("exec GetTaskList Command result is:{}.", ret);
        }
    }
    client_->disconnect();
    thread.join();
    logger_->info("{} exit.", __FUNCTION__);
}

bool CClient::get_task_list()
{
    logger_->info("{} start.", __FUNCTION__);
    char* send = nullptr;
    int len{};
    std::shared_ptr<CFrameBuffer> buf = std::make_shared<CFrameBuffer>();
    buf->data_ = new char[512]{};
    auto flen = std::snprintf(buf->data_, 512, "%s", gGetTaskList);
    buf->len_ = flen;
    buf->type_ = 1;
    if (!CTransProtocal::pack(buf.get(), &send, len)) {
        logger_->error("{} pack failed.", __FUNCTION__);
        return false;
    }
    if (!client_->send(send, len)) {
        return false;
    }
    delete[] send;
    return true;
}

void CClient::handle_data(CFrameBuffer* buf)
{
    if (buf == nullptr) {
        logger_->error("{} nullptr.", __FUNCTION__);
        return;
    }
    logger_->debug("type: {}", buf->type_);
    logger_->debug("len: {}", buf->len_);
}