aboutsummaryrefslogtreecommitdiff
path: root/src/Command.cpp
blob: fb4c0cbef642256e166b7566c6cf7c72fac15d9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "../include/Command.hpp"

using namespace std;

namespace dchat
{
    static unordered_map<string, CommandHandlerFunc> commandHandlerFuncs;
    
    bool Command::add(const string &cmd, CommandHandlerFunc handlerFunc)
    {
        auto it = commandHandlerFuncs.find(cmd);
        if(it != commandHandlerFuncs.end())
            return false;
        
        commandHandlerFuncs[cmd] = handlerFunc;
        return true;
    }
    
    bool Command::call(const string &cmd, const vector<string> &args)
    {
        auto it = commandHandlerFuncs.find(cmd);
        if(it != commandHandlerFuncs.end())
        {
            try
            {
                it->second(args);
            }
            catch(exception &e)
            {
                fprintf(stderr, "Failed while executing command %s, reason: %s\n", cmd.c_str(), e.what());
            }
            return true;
        }
        return false;
    }
    
    const std::unordered_map<std::string, CommandHandlerFunc>& Command::getCommands()
    {
        return commandHandlerFuncs;
    }
}