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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use std::{
    future::Future,
    pin::Pin,
    sync::{
        atomic::{AtomicI32, Ordering},
        Arc,
    },
    task::{Context, Poll},
};

#[cfg(feature = "brs")]
use brickadia::save;

use dashmap::{mapref::entry::Entry, DashMap};
use events::{BrickInteraction, Event};
use resources::{GhostBrick, Player, PlayerPaint, Plugin, TemplateBounds};
use serde_json::{json, Value};
use thiserror::Error;
use tokio::{
    io::{stdin, AsyncBufReadExt, BufReader},
    sync::{
        mpsc::{self, UnboundedReceiver},
        oneshot,
    },
};

use crate::resources::PlayerPosition;

pub mod events;
pub mod resources;
pub mod rpc;

pub type EventReceiver = UnboundedReceiver<Event>;

/// A future that waits for the server to respond, returning a [`Response`](crate::Response).
/// This will await indefinitely, so use with Tokio's `select!` macro to impose a timeout.
pub struct ResponseAwaiter(oneshot::Receiver<rpc::Response>);

impl Future for ResponseAwaiter {
    type Output = Result<Option<Value>, ResponseError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        match Pin::new(&mut self.0).poll(cx) {
            // we received a response, filter between a real result or an RPC error
            Poll::Ready(Ok(response)) => Poll::Ready(match response.error {
                Some(e) => Err(ResponseError::Rpc(e)),
                None => Ok(response.result),
            }),

            // no response received, the channel errored
            Poll::Ready(Err(error)) => Poll::Ready(Err(ResponseError::Recv(error))),

            // we are still waiting
            Poll::Pending => Poll::Pending,
        }
    }
}

/// A response error. Either an RPC error (`rpc::Error`), or a receive error (`oneshot::error::RecvError`).
#[derive(Error, Debug)]
pub enum ResponseError {
    #[error("rpc error")]
    Rpc(rpc::Error),

    #[error("receive error")]
    Recv(#[from] oneshot::error::RecvError),
}

pub struct Omegga {
    pub awaiter_txs: Arc<DashMap<rpc::RequestId, oneshot::Sender<rpc::Response>>>,
    request_id: Arc<AtomicI32>,
}

impl Omegga {
    /// Create a new Omegga instance.
    pub fn new() -> Self {
        Self {
            awaiter_txs: Arc::new(DashMap::new()),
            request_id: Arc::new(AtomicI32::new(-1)),
        }
    }

    /// Spawn the listener.
    pub fn spawn(&self) -> EventReceiver {
        let (tx, rx) = mpsc::unbounded_channel::<Event>();
        let awaiter_txs = Arc::clone(&self.awaiter_txs);
        tokio::spawn(async move {
            let reader = BufReader::new(stdin());
            let mut lines = reader.lines();
            while let Some(line) = lines.next_line().await.unwrap() {
                let message: rpc::Message = match serde_json::from_str(&line) {
                    Ok(v) => v,
                    Err(_) => continue,
                };

                match message {
                    // Handle responses
                    rpc::Message::Response {
                        id, result, error, ..
                    } => {
                        if let Entry::Occupied(entry) = awaiter_txs.entry(id) {
                            let (id, sender) = entry.remove_entry();
                            let _ = sender.send(rpc::Response { id, result, error });
                        }
                    }
                    // Handle requests
                    rpc::Message::Request {
                        id, method, params, ..
                    } => match method.as_str() {
                        "init" => {
                            let _ = tx.send(Event::Init {
                                id,
                                config: params.unwrap_or(Value::Null),
                            });
                        }
                        "stop" => {
                            let _ = tx.send(Event::Stop { id });
                        }
                        "plugin:emit" => match params {
                            Some(Value::Array(v)) => {
                                let mut params = v.into_iter();
                                let event = match params.next().unwrap() {
                                    Value::String(s) => s,
                                    _ => continue,
                                };
                                let from = match params.next().unwrap() {
                                    Value::String(s) => s,
                                    _ => continue,
                                };

                                let _ = tx.send(Event::PluginEmit {
                                    id,
                                    event,
                                    from,
                                    args: params.collect(),
                                });
                            }
                            _ => (),
                        },
                        _ => (),
                    },
                    // Handle notifications
                    rpc::Message::Notification { method, params, .. } => match method.as_str() {
                        "bootstrap" => {
                            let _ = tx.send(Event::Bootstrap {
                                omegga: params.unwrap_or(Value::Null),
                            });
                        }
                        "plugin:players:raw" => {
                            let _ = tx.send(Event::PluginPlayersRaw {
                                players: serde_json::from_value(params.unwrap())
                                    .unwrap_or_default(),
                            });
                        }
                        "line" => {
                            let _ = tx.send(Event::Line(
                                serde_json::from_value::<Vec<String>>(params.unwrap())
                                    .unwrap()
                                    .into_iter()
                                    .next()
                                    .unwrap(),
                            ));
                        }
                        "start" => {
                            #[derive(serde::Deserialize)]
                            struct MapParams {
                                map: String,
                            }

                            let _ = tx.send(Event::Start {
                                map: serde_json::from_value::<Vec<MapParams>>(params.unwrap())
                                    .unwrap()
                                    .into_iter()
                                    .next()
                                    .unwrap()
                                    .map,
                            });
                        }
                        "host" => {
                            #[derive(serde::Deserialize)]
                            struct HostParams {
                                name: String,
                                id: String,
                            }

                            let host = serde_json::from_value::<Vec<HostParams>>(params.unwrap())
                                .unwrap()
                                .into_iter()
                                .next()
                                .unwrap();

                            let _ = tx.send(Event::Host {
                                name: host.name,
                                id: host.id,
                            });
                        }
                        "version" => {
                            let _ = tx.send(Event::Version(params.unwrap()));
                        }
                        "unauthorized" => {
                            let _ = tx.send(Event::Unauthorized);
                        }
                        "join" => {
                            let _ = tx.send(Event::Join(
                                serde_json::from_value::<Vec<_>>(params.unwrap())
                                    .unwrap()
                                    .into_iter()
                                    .next()
                                    .unwrap(),
                            ));
                        }
                        "leave" => {
                            let _ = tx.send(Event::Leave(
                                serde_json::from_value::<Vec<_>>(params.unwrap())
                                    .unwrap()
                                    .into_iter()
                                    .next()
                                    .unwrap(),
                            ));
                        }
                        e if e.starts_with("cmd:") => {
                            let c = &e[4..];
                            let mut params = serde_json::from_value::<Vec<String>>(params.unwrap())
                                .unwrap()
                                .into_iter();

                            let _ = tx.send(Event::Command {
                                player: params.next().unwrap(),
                                command: c.to_string(),
                                args: params.collect(),
                            });
                        }
                        e if e.starts_with("chatcmd:") => {
                            let c = &e[8..];
                            let mut params = serde_json::from_value::<Vec<String>>(params.unwrap())
                                .unwrap()
                                .into_iter();

                            let _ = tx.send(Event::ChatCommand {
                                player: params.next().unwrap(),
                                command: c.to_string(),
                                args: params.collect(),
                            });
                        }
                        "chat" => {
                            let mut params = serde_json::from_value::<Vec<String>>(params.unwrap())
                                .unwrap()
                                .into_iter();

                            let _ = tx.send(Event::Chat {
                                player: params.next().unwrap(),
                                message: params.next().unwrap(),
                            });
                        }
                        "mapchange" => {
                            #[derive(serde::Deserialize)]
                            struct MapParams {
                                map: String,
                            }

                            let _ = tx.send(Event::MapChange(
                                serde_json::from_value::<Vec<MapParams>>(params.unwrap())
                                    .unwrap()
                                    .into_iter()
                                    .next()
                                    .unwrap()
                                    .map,
                            ));
                        }
                        "interact" => {
                            let _ = tx.send(Event::Interact(
                                serde_json::from_value::<BrickInteraction>(params.unwrap())
                                    .unwrap(),
                            ));
                        }
                        e if e.starts_with("event:") => {
                            let e = &e[6..];
                            match params {
                                Some(Value::Array(params)) => {
                                    let mut params = params.into_iter();
                                    let player =
                                        serde_json::from_value::<Player>(params.next().unwrap())
                                            .unwrap();
                                    let args = params
                                        .map(|a| String::from(a.as_str().unwrap()))
                                        .collect::<Vec<_>>();

                                    let _ = tx.send(Event::Event {
                                        name: String::from(e),
                                        player,
                                        args,
                                    });
                                }
                                _ => continue,
                            }
                        }
                        "autorestart" => {
                            let _ = tx.send(Event::Autorestart(params.unwrap_or_default()));
                        }
                        _ => (),
                    },
                };
            }
        });
        rx
    }

    /// Write out an RPC message.
    pub fn write(&self, message: rpc::Message) {
        println!("{}", serde_json::to_string(&message).unwrap());
    }

    /// Write out an RPC notification.
    pub fn write_notification(&self, method: impl Into<String>, params: Option<Value>) {
        self.write(rpc::Message::notification(method.into(), params));
    }

    /// Write out an RPC response.
    pub fn write_response(
        &self,
        id: rpc::RequestId,
        params: Option<Value>,
        error: Option<rpc::Error>,
    ) {
        self.write(rpc::Message::response(id, params, error));
    }

    /// Write out an RPC request.
    ///
    /// **Note:** This does not internally expect a response from the server.
    /// Prefer using [`request`](Omegga::request) over this for the ability to
    /// await a response from the RPC server.
    pub fn write_request(
        &self,
        id: rpc::RequestId,
        method: impl Into<String>,
        params: Option<Value>,
    ) {
        self.write(rpc::Message::request(id, method.into(), params));
    }

    /// Request a response from the RPC server.
    /// This returns a `ResponseAwaiter`, a `Future` that awaits a response.
    pub fn request(&self, method: impl Into<String>, params: Option<Value>) -> ResponseAwaiter {
        // fetch the next ID
        let id = self.request_id.fetch_sub(-1, Ordering::SeqCst);

        // write out the request
        self.write_request(rpc::RequestId::Int(id), method, params);

        // create a channel to send the response over
        let (tx, rx) = oneshot::channel::<rpc::Response>();

        // insert the transmitter into the dashmap
        self.awaiter_txs.insert(rpc::RequestId::Int(id), tx);

        // return back with an awaiter to await the receiver
        ResponseAwaiter(rx)
    }

    /// Register commands with Omegga. Call when the plugin is initialized.
    pub fn register_commands(&self, id: rpc::RequestId, commands: &[&str]) {
        self.write_response(id, Some(json!({ "registeredCommands": commands })), None);
    }

    /// Prints a message to the Omegga console.
    pub fn log(&self, line: impl Into<String>) {
        self.write_notification("log", Some(Value::String(line.into())));
    }

    /// Prints a message to the Omegga console in error color.
    pub fn error(&self, line: impl Into<String>) {
        self.write_notification("error", Some(Value::String(line.into())));
    }

    /// Prints a message to the Omegga console in info color.
    pub fn info(&self, line: impl Into<String>) {
        self.write_notification("info", Some(Value::String(line.into())));
    }

    /// Prints a message to the Omegga console in warn color.
    pub fn warn(&self, line: impl Into<String>) {
        self.write_notification("warn", Some(Value::String(line.into())));
    }

    /// Prints a message to the Omegga console in trace color.
    pub fn trace(&self, line: impl Into<String>) {
        self.write_notification("trace", Some(Value::String(line.into())));
    }

    /// Gets an object from the store.
    pub async fn store_get(&self, key: impl Into<String>) -> Result<Option<Value>, ResponseError> {
        self.request("store.get", Some(Value::String(key.into())))
            .await
    }

    /// Sets an object in the store.
    pub fn store_set(&self, key: impl Into<String>, value: Value) {
        self.write_notification("store.set", Some(json!([key.into(), value])))
    }

    /// Deletes an object from the store.
    pub async fn store_delete(&self, key: impl Into<String>) {
        self.write_notification("store.delete", Some(Value::String(key.into())))
    }

    /// Wipes the store.
    pub fn store_wipe(&self) {
        self.write_notification("store.wipe", None)
    }

    /// Gets a list of keys in the store.
    pub async fn store_keys(&self) -> Result<Vec<String>, ResponseError> {
        self.request("store.keys", None).await.map(|r| match r {
            Some(r) => serde_json::from_value::<Vec<String>>(r).unwrap_or_else(|_| vec![]),
            None => vec![],
        })
    }

    /// Writes a line out to the Brickadia server.
    pub fn writeln(&self, line: impl Into<String>) {
        self.write_notification("exec", Some(Value::String(line.into())));
    }

    /// Broadcasts a line.
    pub fn broadcast(&self, line: impl Into<String>) {
        self.write_notification("broadcast", Some(Value::String(line.into())));
    }

    /// Whispers a line to a user by their name.
    pub fn whisper(&self, username: impl Into<String>, line: impl Into<String>) {
        self.write_notification(
            "whisper",
            Some(json!({"target": username.into(), "line": line.into()})),
        );
    }

    pub fn middle_print(&self, username: impl Into<String>, line: impl Into<String>) {
        self.write_notification(
            "middlePrint",
            Some(json!({"target": username.into(), "line": line.into()})),
        );
    }

    /// Gets a list of all players.
    pub async fn get_players(&self) -> Result<Vec<Player>, ResponseError> {
        self.request("getPlayers", None).await.map(|r| match r {
            Some(r) => serde_json::from_value::<Vec<Player>>(r).unwrap_or_else(|_| vec![]),
            None => vec![],
        })
    }

    /// Get all player positions.
    pub async fn get_all_player_positions(&self) -> Result<Vec<PlayerPosition>, ResponseError> {
        self.request("getAllPlayerPositions", None)
            .await
            .map(|r| match r {
                Some(r) => {
                    serde_json::from_value::<Vec<PlayerPosition>>(r).unwrap_or_else(|_| vec![])
                }
                None => vec![],
            })
    }

    /// Get the role setup.
    pub async fn get_role_setup(&self) -> Result<Value, ResponseError> {
        // TODO: write a type for this instead of using a serde_json::Value
        self.request("getRoleSetup", None).await.map(Option::unwrap)
    }

    /// Get the ban list.
    pub async fn get_ban_list(&self) -> Result<Value, ResponseError> {
        // TODO: write a type for this instead of using a serde_json::Value
        self.request("getBanList", None).await.map(Option::unwrap)
    }

    /// Get a list of the server's saves.
    pub async fn get_saves(&self) -> Result<Vec<String>, ResponseError> {
        self.request("getSaves", None).await.map(|r| match r {
            Some(r) => serde_json::from_value::<Vec<String>>(r).unwrap_or_else(|_| vec![]),
            None => vec![],
        })
    }

    /// Get the path to a specific save.
    pub async fn get_save_path(
        &self,
        save: impl Into<String>,
    ) -> Result<Option<String>, ResponseError> {
        self.request("getSavePath", Some(Value::String(save.into())))
            .await
            .map(|r| match r {
                Some(r) => serde_json::from_value::<String>(r).ok(),
                None => None,
            })
    }

    /// Gets the server's current save data.
    #[cfg(not(feature = "brs"))]
    pub async fn get_save_data(&self) -> Result<Value, ResponseError> {
        self.request("getSaveData", None).await.map(Option::unwrap)
    }

    /// Gets the server's current save data as a brickadia-rs save object.
    #[cfg(feature = "brs")]
    pub async fn get_save_data(&self) -> Result<save::SaveData, ResponseError> {
        self.request("getSaveData", None)
            .await
            .map(|r| serde_json::from_value::<save::SaveData>(r.unwrap()).unwrap())
    }

    /// Clears a player's bricks by their name.
    pub fn clear_bricks(&self, target: impl Into<String>, quiet: bool) {
        self.write_notification(
            "clearBricks",
            Some(json!({"target": target.into(), "quiet": quiet})),
        );
    }

    /// Clear all bricks.
    pub fn clear_all_bricks(&self, quiet: bool) {
        self.write_notification("clearAllBricks", Some(json!({ "quiet": quiet })));
    }

    /// Save bricks to a named save.
    pub async fn save_bricks(&self, name: impl Into<String>) -> Result<(), ResponseError> {
        self.request("saveBricks", Some(Value::String(name.into())))
            .await
            .map(|_| ())
    }

    /// Load a save, provided an offset in the world.
    pub async fn load_bricks(
        &self,
        name: impl Into<String>,
        quiet: bool,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadBricks", Some(json!({"name": name.into(), "quiet": quiet, "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Load a save onto a player's clipboard.
    pub async fn load_bricks_on_player(
        &self,
        name: impl Into<String>,
        player: impl Into<String>,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadBricksOnPlayer", Some(json!({"name": name.into(), "player": player.into(), "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Reads a save (from a save file), and returns its data.
    #[cfg(not(feature = "brs"))]
    pub async fn read_save_data(
        &self,
        name: impl Into<String>,
    ) -> Result<Option<Value>, ResponseError> {
        self.request("readSaveData", Some(Value::String(name.into())))
            .await
    }

    /// Reads a save (from a save file), and returns its data as a brickadia-rs save object.
    #[cfg(feature = "brs")]
    pub async fn read_save_data(
        &self,
        name: impl Into<String>,
    ) -> Result<Option<save::SaveData>, ResponseError> {
        self.request("readSaveData", Some(Value::String(name.into())))
            .await
            .map(|r| match r {
                Some(r) => serde_json::from_value::<save::SaveData>(r).ok(),
                None => None,
            })
    }

    /// Loads a save (from a JSON value) into the world, provided an offset.
    #[cfg(not(feature = "brs"))]
    pub async fn load_save_data(
        &self,
        data: Value,
        quiet: bool,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadSaveData", Some(json!({"data": data, "quiet": quiet, "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Loads a save (from brickadia-rs save data) into the world, provided an offset.
    #[cfg(feature = "brs")]
    pub async fn load_save_data(
        &self,
        data: save::SaveData,
        quiet: bool,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadSaveData", Some(json!({"data": data, "quiet": quiet, "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Loads a save (from a JSON value) onto a player's clipboard.
    #[cfg(not(feature = "brs"))]
    pub async fn load_save_data_on_player(
        &self,
        data: Value,
        player: impl Into<String>,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadSaveDataOnPlayer", Some(json!({"data": data, "player": player.into(), "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Loads a save (from brickadia-rs save data) onto a player's clipboard.
    #[cfg(feature = "brs")]
    pub async fn load_save_data_on_player(
        &self,
        data: save::SaveData,
        player: impl Into<String>,
        offset: (i32, i32, i32),
    ) -> Result<(), ResponseError> {
        self.request("loadSaveDataOnPlayer", Some(json!({"data": data, "player": player.into(), "offX": offset.0, "offY": offset.1, "offZ": offset.2}))).await.map(|_| ())
    }

    /// Changes the map.
    pub async fn change_map(&self, map: impl Into<String>) -> Result<(), ResponseError> {
        self.request("changeMap", Some(Value::String(map.into())))
            .await
            .map(|_| ())
    }

    /// Get a player.
    pub async fn get_player(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<Player>, ResponseError> {
        self.request("player.get", Some(Value::String(target.into())))
            .await
            .map(|r| serde_json::from_value::<Player>(r.unwrap_or(Value::Null)).ok())
    }

    /// Get a player's roles.
    pub async fn get_player_roles(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<Vec<String>>, ResponseError> {
        self.request("player.getRoles", Some(Value::String(target.into())))
            .await
            .map(|r| serde_json::from_value::<Vec<String>>(r.unwrap_or(Value::Null)).ok())
    }

    /// Get a player's permissions.
    pub async fn get_player_permissions(
        &self,
        target: impl Into<String>,
    ) -> Result<Value, ResponseError> {
        self.request("player.getPermissions", Some(Value::String(target.into())))
            .await
            .map(|r| r.unwrap_or(Value::Null))
    }

    /// Get a player's name color (6-digit hexadecimal).
    pub async fn get_player_name_color(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<String>, ResponseError> {
        self.request("player.getNameColor", Some(Value::String(target.into())))
            .await
            .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Get a player's position.
    pub async fn get_player_position(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<(f64, f64, f64)>, ResponseError> {
        self.request("player.getPosition", Some(Value::String(target.into())))
            .await
            .map(|r| match r {
                Some(r) => serde_json::from_value::<(f64, f64, f64)>(r).ok(),
                None => None,
            })
    }

    /// Get a player's ghost brick data.
    pub async fn get_player_ghost_brick(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<GhostBrick>, ResponseError> {
        self.request("player.getGhostBrick", Some(Value::String(target.into())))
            .await
            .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Get a player's paint data.
    pub async fn get_player_paint(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<PlayerPaint>, ResponseError> {
        self.request("player.getPaint", Some(Value::String(target.into())))
            .await
            .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Get a player's template bounds.
    pub async fn get_player_template_bounds(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<TemplateBounds>, ResponseError> {
        self.request(
            "player.getTemplateBounds",
            Some(Value::String(target.into())),
        )
        .await
        .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Get a player's template data.
    #[cfg(not(feature = "brs"))]
    pub async fn get_player_template_bounds_data(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<Value>, ResponseError> {
        self.request(
            "player.getTemplateBoundsData",
            Some(Value::String(target.into())),
        )
        .await
    }

    /// Get a player's template data as a brickadia-rs save object.
    #[cfg(feature = "brs")]
    pub async fn get_player_template_bounds_data(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<save::SaveData>, ResponseError> {
        self.request(
            "player.getTemplateBoundsData",
            Some(Value::String(target.into())),
        )
        .await
        .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Load save data at a player's template.
    #[cfg(not(feature = "brs"))]
    pub async fn load_data_at_ghost_brick(
        &self,
        target: impl Into<String>,
        data: Value,
        offset: (i32, i32, i32),
        rotate: bool,
        quiet: bool,
    ) -> Result<(), ResponseError> {
        self.request("player.loadDataAtGhostBrick", Some(json!({"target": target.into(), "data": data, "offX": offset.0, "offY": offset.1, "offZ": offset.2, "rotate": rotate, "quiet": quiet})))
            .await
            .map(|_| ())
    }

    /// Load brickadia-rs save data at a player's template.
    #[cfg(feature = "brs")]
    pub async fn load_data_at_ghost_brick(
        &self,
        target: impl Into<String>,
        data: save::SaveData,
        offset: (i32, i32, i32),
        rotate: bool,
        quiet: bool,
    ) -> Result<(), ResponseError> {
        self.request("player.loadDataAtGhostBrick", Some(json!({"target": target.into(), "data": data, "offX": offset.0, "offY": offset.1, "offZ": offset.2, "rotate": rotate, "quiet": quiet})))
            .await
            .map(|_| ())
    }

    /// Get a plugin.
    pub async fn get_plugin(
        &self,
        target: impl Into<String>,
    ) -> Result<Option<Plugin>, ResponseError> {
        self.request("plugin.get", Some(Value::String(target.into())))
            .await
            .map(|r| r.and_then(|r| serde_json::from_value::<_>(r).ok()))
    }

    /// Emit a custom event to a plugin.
    pub async fn emit_plugin<T>(
        &self,
        target: String,
        event: String,
        args: Vec<Value>,
    ) -> Result<Option<T>, ResponseError>
    where
        T: serde::de::DeserializeOwned,
    {
        let mut query = vec![Value::String(target.into()), Value::String(event.into())];
        query.extend(args.into_iter());

        self.request("plugin.emit", Some(Value::Array(query)))
            .await
            .map(|r| {
                serde_json::from_value::<_>(r.unwrap_or_default())
                    .ok()
                    .unwrap_or_default()
            })
    }
}

impl Default for Omegga {
    fn default() -> Self {
        Self::new()
    }
}