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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use crate::{
    checks::ENABLED_CHECK,
    util::AsciiTable,
    ClientDataKey,
};
use anyhow::Context as _;
use serenity::{
    framework::standard::{
        macros::command,
        Args,
        CommandResult,
    },
    model::prelude::*,
    prelude::*,
};
use tracing::error;

#[command]
#[description("Get personal stats for Tic-Tac-Toe")]
#[checks(Enabled)]
#[bucket("default")]
pub async fn stats(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
    let data_lock = ctx.data.read().await;
    let client_data = data_lock
        .get::<ClientDataKey>()
        .expect("missing client data");
    let db = client_data.db.clone();
    drop(data_lock);

    let scores = match db
        .get_tic_tac_toe_score(msg.guild_id.into(), msg.author.id)
        .await
        .context("failed to get tic-tac-toe stats")
    {
        Ok(scores) => scores,
        Err(e) => {
            error!("{:?}", e);
            msg.channel_id.say(&ctx.http, format!("{:?}", e)).await?;
            return Ok(());
        }
    };

    let mut table = AsciiTable::new(4, 2);
    table.set_padding(2);

    let mut wins_buffer = itoa::Buffer::new();
    let mut losses_buffer = itoa::Buffer::new();
    let mut ties_buffer = itoa::Buffer::new();
    let mut concedes_buffer = itoa::Buffer::new();

    table.set_cell(0, 0, "Wins");
    table.set_cell(1, 0, "Losses");
    table.set_cell(2, 0, "Ties");
    table.set_cell(3, 0, "Concedes");

    table.set_cell(0, 1, wins_buffer.format(scores.wins));
    table.set_cell(1, 1, losses_buffer.format(scores.losses));
    table.set_cell(2, 1, ties_buffer.format(scores.ties));
    table.set_cell(3, 1, concedes_buffer.format(scores.concedes));

    msg.channel_id
        .say(
            &ctx.http,
            format!(
                "```\n{}'s Tic-Tac-Toe Stats\n{}\n```",
                msg.author.name, table
            ),
        )
        .await?;
    Ok(())
}