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
//! (Current incomplete) interface for minecraft's text commands.

use std::{fmt, rc::Rc};

use itertools::Itertools;

use crate::block_id::BlockId;

use super::minecraft_utils::ScoreboardValue;

/// Debris syntax:
/// `normal text $variable other text $other_variable, end after non-ident char \& 4escaped ampersand`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormattedText {
    pub components: Vec<JsonFormatComponent>,
}

impl fmt::Display for FormattedText {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"")?;
        f.write_str(
            &self
                .components
                .iter()
                .map(JsonFormatComponent::to_string)
                .join(""),
        )?;
        write!(f, "\"")
    }
}

impl From<Vec<JsonFormatComponent>> for FormattedText {
    fn from(value: Vec<JsonFormatComponent>) -> Self {
        FormattedText { components: value }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsonFormatComponent {
    RawText(Rc<str>),
    Score(ScoreboardValue),
    Function(BlockId),
}

impl fmt::Display for JsonFormatComponent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JsonFormatComponent::RawText(text) => f.write_str(text),
            JsonFormatComponent::Score(value) => match value {
                ScoreboardValue::Static(int) => write!(f, "{int}"),
                ScoreboardValue::Scoreboard(value) => {
                    write!(f, "{{{{{value}}}}}")
                }
            },
            JsonFormatComponent::Function(function) => write!(f, "{{call {function}}}"),
        }
    }
}