aboutsummaryrefslogtreecommitdiff
path: root/src/methods/execute_command.zig
blob: add17e9b47cee35949a5141dddb5168a7ccf07f5 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
const std = @import("std");

const engine = @import("../engine.zig");

const Allocator = std.mem.Allocator;

pub const method = .{
    .name = "execute_command",
    .func = execute_command,
};

fn execute_command(allocator: Allocator, params: ?std.json.Value) !?std.json.Value {
    if (params == null) {
        return error.InvalidParameters;
    }

    const command = blk: {
        const command_item = switch (params.?) {
            .array => param_blk: {
                const command_array = params.?.array;

                if (command_array.capacity < 1) {
                    return error.NoCommand;
                }

                break :param_blk command_array.items[0];
            },

            .object => param_blk: {
                const command_object = params.?.object;

                break :param_blk command_object.get("command") orelse return error.NoCommand;
            },

            else => return error.NoCommand,
        };

        if (command_item != .string) {
            return error.InvalidCommand;
        }

        break :blk try allocator.dupeZ(u8, command_item.string);
    };
    defer allocator.free(command);

    if (engine.Cbuf) |Cbuf| {
        const cur_player = Cbuf.GetCurrentPlayer();
        Cbuf.AddText(cur_player, command, .kCommandSrcCode);
    } else {
        return error.NoEngine;
    }

    return null;
}