// SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later

#include "actor.h"

Module::Actor::Actor(const std::shared_ptr<Core>& core, const Config::Module& conf):
    Module(core, conf, "Actor")
{}

Module::Actor::~Actor() noexcept {}

Shared::Result Module::Actor::message(const std::shared_ptr<::Actor>& actor, std::string_view view) {
    std::string_view command = pop(view);

    if (command == "list") {
        if (!hasPermission("read", actor))
            return Shared::forbidden;
            
        core->send(actor->jid, list());
        return Shared::success;
    } 

    if (command == "set") {
        if (!hasPermission("write", actor))
            return Shared::forbidden;
        
        std::string_view jid = pop(view);
        std::string_view group = pop(view);
        if (jid.empty() || group.empty())
            return Shared::error;

        core->send(actor->jid, set(jid, group));
        return Shared::success;
    }

    return Shared::unhandled;
}

std::string Module::Actor::list() {
    std::string result;
    for (const std::pair<const std::string, std::string>& pair : core->router.getActors()) {
        if (!result.empty())
            result.append(1, '\n');

        result += pair.first + ": " + pair.second;
    }

    if (result.empty())
        result += "There are no actors currently";

    return result;
}

std::string Module::Actor::set(const std::string_view& jid, const std::string_view& group) {
    std::string j(lower(std::string(jid)));
    std::string g(group);
    
    core->setGroup(j, g);

    return j + " is now " + core->router.getGroup(j);
}