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
72
73
74
75
76
77
78
79
80
81
82
use common::comp::Content;
use hashbrown::HashMap;
use std::fmt;
use vek::*;

#[derive(Debug)]
pub enum LocationError<'a> {
    InvalidName(String),
    DuplicateName(String),
    DoesNotExist(&'a str),
}

impl<'a> From<LocationError<'a>> for Content {
    fn from(value: LocationError<'a>) -> Self {
        match value {
            LocationError::InvalidName(location) => {
                Content::localized_with_args("command-location-invalid", [("location", location)])
            },
            LocationError::DuplicateName(location) => {
                Content::localized_with_args("command-location-duplicate", [("location", location)])
            },
            LocationError::DoesNotExist(location) => {
                Content::localized_with_args("command-location-not-found", [("location", location)])
            },
        }
    }
}

impl<'a> fmt::Display for LocationError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidName(name) => write!(
                f,
                "Location name '{}' is invalid. Names may only contain lowercase ASCII and \
                 underscores",
                name
            ),
            Self::DuplicateName(name) => write!(
                f,
                "Location '{}' already exists, consider deleting it first",
                name
            ),
            Self::DoesNotExist(name) => write!(f, "Location '{}' does not exist", name),
        }
    }
}

/// Locations are moderator-defined positions that can be teleported between by
/// players. They currently do not persist between server sessions.
#[derive(Default)]
pub struct Locations {
    locations: HashMap<String, Vec3<f32>>,
}

impl Locations {
    pub fn insert(&mut self, name: String, pos: Vec3<f32>) -> Result<(), LocationError<'static>> {
        if name.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
            self.locations
                .try_insert(name, pos)
                .map(|_| ())
                .map_err(|o| LocationError::DuplicateName(o.entry.key().clone()))
        } else {
            Err(LocationError::InvalidName(name))
        }
    }

    pub fn get<'a>(&self, name: &'a str) -> Result<Vec3<f32>, LocationError<'a>> {
        self.locations
            .get(name)
            .copied()
            .ok_or(LocationError::DoesNotExist(name))
    }

    pub fn iter(&self) -> impl Iterator<Item = &String> { self.locations.keys() }

    pub fn remove<'a>(&mut self, name: &'a str) -> Result<(), LocationError<'a>> {
        self.locations
            .remove(name)
            .map(|_| ())
            .ok_or(LocationError::DoesNotExist(name))
    }
}