#include "SendManager.hpp"

#include <iostream>

#include "behavior/tasks/client/ClientTask.hpp"
#include "behavior/tasks/server/ServerTask.hpp"
#include "behavior/tasks/undefined/UndefinedTask.hpp"


namespace drp::managers {


SendManager::SendManager(const std::shared_ptr<Context>& context) {
    this->context = context;

    // register the different tasks type
    this->registry = {
        {task::TaskType::UNDEFINED, std::make_shared<task::UndefinedTask>()},
        {task::TaskType::CLIENT, std::make_shared<task::ClientTask>()},
        {task::TaskType::SERVER, std::make_shared<task::ServerTask>()},
    };
}


void SendManager::run() const {
    std::cout << "[Sender] Handling status: " + std::to_string(static_cast<int>(this->context->me.status)) << std::endl;

    // get the corresponding task class
    std::shared_ptr<task::BaseTask> task;
    try {
        task = this->registry.at(this->context->me.status);
    } catch (const std::out_of_range& exception) {
        std::cerr << "[Sender] Unsupported status: " << std::to_string(static_cast<int>(this->context->me.status)) << std::endl;
        return;
    }

    // ask the task class to handle the task
    try {
        task->handle(*this->context);
    } catch (const std::exception& exception) {
        std::cerr << "[Sender] Unhandled exception: " << exception.what() << std::endl;
    }
}


void SendManager::loop() const {
    while (true)
        this->run();
}


}
