aboutsummaryrefslogtreecommitdiff
path: root/karlgui/src/globals.rs
diff options
context:
space:
mode:
Diffstat (limited to 'karlgui/src/globals.rs')
-rw-r--r--karlgui/src/globals.rs96
1 files changed, 96 insertions, 0 deletions
diff --git a/karlgui/src/globals.rs b/karlgui/src/globals.rs
new file mode 100644
index 0000000..202cce6
--- /dev/null
+++ b/karlgui/src/globals.rs
@@ -0,0 +1,96 @@
+use crate::{client::Client, helper::from_timestamp};
+use chrono::NaiveDateTime;
+use karlcommon::{ClientboundPacket, ServerboundPacket, Task};
+use log::warn;
+use std::{
+ collections::{HashMap, VecDeque},
+ ops::Range,
+};
+
+pub struct Globals {
+ pub client: Client,
+ pub tasks: HashMap<u64, Task>,
+ pub awaiting_instance_requests: VecDeque<(u64, Range<NaiveDateTime>)>,
+
+ pub instance_cache:
+ HashMap<(u64, Range<NaiveDateTime>), Option<Vec<Range<Option<NaiveDateTime>>>>>,
+}
+
+impl Globals {
+ pub fn new(client: Client) -> Self {
+ Globals {
+ client,
+ tasks: Default::default(),
+ instance_cache: Default::default(),
+ awaiting_instance_requests: Default::default(),
+ }
+ }
+ pub fn update_network(&mut self) {
+ for p in self.client.receiver.try_iter() {
+ match p {
+ ClientboundPacket::TaskList(t) => {
+ self.tasks = HashMap::from_iter(t.into_iter().map(|e| (e.id, e)));
+ }
+ ClientboundPacket::Sync => {
+ self.client.busy = false;
+ }
+ ClientboundPacket::InstanceList(is) => {
+ if let Some(i) = self.awaiting_instance_requests.pop_front() {
+ self.instance_cache.insert(
+ i,
+ Some(
+ is.iter()
+ .map(|r| r.start.map(from_timestamp)..r.end.map(from_timestamp))
+ .collect(),
+ ),
+ );
+ } else {
+ warn!("got unknown instance list packet")
+ }
+ }
+ _ => {}
+ }
+ }
+ }
+ pub fn get_all_instances_range(
+ &mut self,
+ start: NaiveDateTime,
+ end: NaiveDateTime,
+ ) -> Option<Vec<(u64, Range<Option<NaiveDateTime>>)>> {
+ let mut l = vec![];
+ for t in &self.tasks.values().map(|e| e.id).collect::<Vec<_>>() {
+ if let Some(r) = self.get_instances_range(*t, start, end) {
+ l.extend(r.into_iter().map(|e| (*t, e.clone())));
+ }
+ }
+ if l.len() > 0 {
+ Some(l)
+ } else {
+ None
+ }
+ }
+ pub fn get_instances_range(
+ &mut self,
+ task: u64,
+ start: NaiveDateTime,
+ end: NaiveDateTime,
+ ) -> &Option<Vec<Range<Option<NaiveDateTime>>>> {
+ // looks silly but the borrow checker likes it more
+ let has = self.instance_cache.contains_key(&(task, start..end));
+ if has {
+ if let Some(c) = self.instance_cache.get(&(task, start..end)) {
+ return c;
+ }
+ return &None;
+ }
+ self.awaiting_instance_requests
+ .push_back((task, start..end));
+ self.instance_cache.insert((task, start..end), None);
+ self.client.send_sync(ServerboundPacket::ListInstances {
+ task,
+ range: Some(start.timestamp())..Some(end.timestamp()),
+ limit: 100,
+ });
+ &None
+ }
+}