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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
use crate::{
    activity::events::ActivityEvent,
    handler::DiscordMsg,
    lobby::events::LobbyEvent,
    overlay::events::OverlayEvent,
    proto::event::ClassifiedEvent,
    relations::events::RelationshipEvent,
    user::{events::UserEvent, User},
    voice::events::VoiceEvent,
};
use tokio::sync::{broadcast, watch};

/// An event wheel, with a different `spoke` per class of events
pub struct Wheel {
    lobby: broadcast::Sender<LobbyEvent>,
    activity: broadcast::Sender<ActivityEvent>,
    relations: broadcast::Sender<RelationshipEvent>,
    voice: broadcast::Sender<VoiceEvent>,

    user: watch::Receiver<UserState>,
    overlay: watch::Receiver<OverlayState>,
}

impl Wheel {
    pub fn new(error: Box<dyn OnError>) -> (Self, WheelHandler) {
        let (lobby_tx, _lobby_rx) = broadcast::channel(10);
        let (activity_tx, _activity_rx) = broadcast::channel(10);
        let (rl_tx, _rl_rx) = broadcast::channel(10);
        let (voice_tx, _voice_rx) = broadcast::channel(10);

        let (user_tx, user_rx) =
            watch::channel(UserState::Disconnected(crate::Error::NoConnection));
        let (overlay_tx, overlay_rx) = watch::channel(OverlayState {
            enabled: false,
            visible: crate::overlay::Visibility::Hidden,
        });

        (
            Self {
                lobby: lobby_tx.clone(),
                activity: activity_tx.clone(),
                relations: rl_tx.clone(),
                user: user_rx,
                overlay: overlay_rx,
                voice: voice_tx.clone(),
            },
            WheelHandler {
                lobby: lobby_tx,
                activity: activity_tx,
                relations: rl_tx,
                user: user_tx,
                overlay: overlay_tx,
                voice: voice_tx,
                error,
            },
        )
    }

    #[inline]
    pub fn lobby(&self) -> LobbySpoke {
        LobbySpoke(self.lobby.subscribe())
    }

    #[inline]
    pub fn activity(&self) -> ActivitySpoke {
        ActivitySpoke(self.activity.subscribe())
    }

    #[inline]
    pub fn relationships(&self) -> RelationshipSpoke {
        RelationshipSpoke(self.relations.subscribe())
    }

    #[inline]
    pub fn user(&self) -> UserSpoke {
        UserSpoke(self.user.clone())
    }

    #[inline]
    pub fn overlay(&self) -> OverlaySpoke {
        OverlaySpoke(self.overlay.clone())
    }

    #[inline]
    pub fn voice(&self) -> VoiceSpoke {
        VoiceSpoke(self.voice.subscribe())
    }
}

pub struct LobbySpoke(pub broadcast::Receiver<LobbyEvent>);
pub struct ActivitySpoke(pub broadcast::Receiver<ActivityEvent>);
pub struct RelationshipSpoke(pub broadcast::Receiver<RelationshipEvent>);
pub struct VoiceSpoke(pub broadcast::Receiver<VoiceEvent>);
pub struct UserSpoke(pub watch::Receiver<UserState>);
pub struct OverlaySpoke(pub watch::Receiver<OverlayState>);

#[async_trait::async_trait]
pub trait OnError: Send + Sync {
    async fn on_error(&self, _error: crate::Error) {}
}

#[async_trait::async_trait]
impl<F> OnError for F
where
    F: Fn(crate::Error) + Send + Sync,
{
    async fn on_error(&self, error: crate::Error) {
        self(error);
    }
}

#[derive(Debug)]
pub enum UserState {
    Connected(User),
    Disconnected(crate::Error),
}

#[derive(Debug)]
pub struct OverlayState {
    /// Whether the user has the overlay enabled or disabled. If the overlay
    /// is disabled, all the functionality of the SDK will still work. The
    /// calls will instead focus the Discord client and show the modal there
    /// instead of in application.
    pub enabled: bool,
    /// Whether the overlay is visible or not.
    pub visible: crate::overlay::Visibility,
}

/// The write part of the [`Wheel`] which is used by the actual handler task
pub struct WheelHandler {
    lobby: broadcast::Sender<LobbyEvent>,
    activity: broadcast::Sender<ActivityEvent>,
    relations: broadcast::Sender<RelationshipEvent>,
    voice: broadcast::Sender<VoiceEvent>,

    user: watch::Sender<UserState>,
    overlay: watch::Sender<OverlayState>,

    error: Box<dyn OnError>,
}

#[async_trait::async_trait]
impl super::DiscordHandler for WheelHandler {
    async fn on_message(&self, msg: DiscordMsg) {
        match msg {
            DiscordMsg::Error(err) => self.error.on_error(err).await,
            DiscordMsg::Event(eve) => match ClassifiedEvent::from(eve) {
                ClassifiedEvent::Lobby(lobby) => {
                    if let Err(e) = self.lobby.send(lobby) {
                        tracing::warn!(event = ?e.0, "Lobby event was unobserved");
                    }
                }
                ClassifiedEvent::User(user) => {
                    let us = match user {
                        UserEvent::Connect(eve) => UserState::Connected(eve.user),
                        UserEvent::Update(eve) => UserState::Connected(eve.user),
                        UserEvent::Disconnect(de) => UserState::Disconnected(de.reason),
                    };

                    if let Err(e) = self.user.send(us) {
                        tracing::warn!(error = %e, "User event was unobserved");
                    }
                }
                ClassifiedEvent::Relations(re) => {
                    if let Err(e) = self.relations.send(re) {
                        tracing::warn!(event = ?e.0, "Relationship event was unobserved");
                    }
                }
                ClassifiedEvent::Activity(activity) => {
                    if let Err(e) = self.activity.send(activity) {
                        tracing::warn!(event = ?e.0, "Activity event was unobserved");
                    }
                }
                ClassifiedEvent::Overlay(overlay) => {
                    let os = match overlay {
                        OverlayEvent::Update(update) => OverlayState {
                            enabled: update.enabled,
                            visible: update.visible,
                        },
                    };

                    if let Err(e) = self.overlay.send(os) {
                        tracing::warn!(error = %e, "Overlay event was unobserved");
                    }
                }
                ClassifiedEvent::Voice(ve) => {
                    let ve = VoiceEvent::Refresh(ve);

                    if let Err(e) = self.voice.send(ve) {
                        tracing::warn!(event = ?e.0, "Voice event was unobserved");
                    }
                }
            },
        }
    }
}