summaryrefslogtreecommitdiffstats
path: root/src/chat.rs
blob: a1ced32280f9f27c89fade02320c5fa891eb4da9 (plain) (blame)
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
use std::ops::{Deref, DerefMut};

use filamento::{chat::Chat, user::User};
use jid::BareJID;
use leptos_fetch::QueryClient;
use reactive_stores::ArcStore;
use leptos::prelude::*;

use crate::{client::Client, user::MacawUser};

async fn get_chat(jid: BareJID) -> ArcStore<Chat> {
    let client: Client = use_context().expect("no client in context");
    ArcStore::new(client.get_chat(jid).await.unwrap())
}

#[derive(Clone)]
pub struct MacawChat {
    pub chat: ArcStore<Chat>,
    pub user: MacawUser,
    // user: StateListener<BareJID, ArcStore<User>>,
}

impl MacawChat {
    pub fn got_chat_and_user(chat: Chat, user: User) -> Self {
        let query_client: QueryClient = expect_context();

        let jid = chat.correspondent.clone();
        let chat_store = query_client.subscribe_value_local(get_chat, move || jid.clone());
        if let Some(chat_store) = chat_store.get() {
            chat_store.set(chat);
            let user = MacawUser::got_user(user);
            Self { chat: chat_store, user }
        } else {
            let jid = chat.correspondent.clone();
            let chat_store = ArcStore::new(chat);
            query_client.set_query_local(get_chat, jid, chat_store.clone());
            let user = MacawUser::got_user(user);
            Self {
                chat: chat_store,
                user,
            }
        }
    }
}

impl Deref for MacawChat {
    type Target = ArcStore<Chat>;

    fn deref(&self) -> &Self::Target {
        &self.chat
    }
}

impl DerefMut for MacawChat {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.chat
    }
}