#include "ClientTask.hpp"

#include <iostream>
#include <thread>


namespace drp::task {


void ClientTask::use(Context& context, const std::shared_ptr<RemotePeer>& server) {
    context.me.status = TaskType::CLIENT;
    context.server = server;
}



void ClientTask::handle(Context& context) {
    // get the server hostname
    char host[NI_MAXHOST];
    char port[NI_MAXSERV];
    getnameinfo(
        reinterpret_cast<sockaddr*>(&context.server->address), context.server->addressLength,
        host, sizeof(host),
        port, sizeof(port),
        NI_NUMERICHOST | NI_NUMERICSERV
    );

    // connect to the chrony server
    // TODO(Faraphel): only once ?
    FILE* chronyProcess = popen(("chronyc add server " + std::string(host) + " iburst 2>&1").c_str(), "r");
    if (pclose(chronyProcess) == -1)
        std::cerr << "[Task - Client] Failed to connect to chrony server !" << std::endl;

    // TODO(Faraphel): check if the server is still reachable.
    //   if connection lost, go back to undefined mode.

    std::this_thread::sleep_for(std::chrono::seconds(1));
}


}
