DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 18acb7d0f8dc4c048b3cf39391845a1b527b8350 deck-builder/client-old-for-ref/src/plugins/menu_old/play/mygamescall.rs -rw-r--r-- 2.2 KiB
18acb7d0 — skye feat!(client): replace gamestate consts with enums 1 year, 8 months ago
                                                                                
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
/*
 * This file is part of sdbclient
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use bevy::{
    prelude::*,
    tasks::{AsyncComputeTaskPool, Task},
};
use bevy_console::PrintConsoleLine;

use futures_lite::future;

use crate::{
    api::{self, game::ResponseMyGames},
    cfg::{CfgDev, CfgUser},
    runtime::menu::RTDMenu,
};

use super::MyGamesEvent;

struct MyGamesCallResponse {
    my_games: ResponseMyGames,
}

#[derive(Component)]
pub(super) struct MyGamesCall(Task<MyGamesCallResponse>);

pub(super) fn start(
    mut events: EventReader<MyGamesEvent>,
    mut commands: Commands,
    cfg_dev: Res<CfgDev>,
    cfg_user: Res<CfgUser>,
    mut rtdmenu: ResMut<RTDMenu>,
) {
    for _event in events.iter() {
        let api_address = cfg_dev.api_server.clone();
        let token = cfg_user.user_token.clone();

        let thread_pool = AsyncComputeTaskPool::get();
        let task = thread_pool.spawn(async move {
            let my_games_response = api::game::my_games(api_address, token);

            MyGamesCallResponse {
                my_games: my_games_response,
            }
        });
        commands.spawn(MyGamesCall(task));
        rtdmenu.waiting_for_my_games_call = true;
    }
}

pub(super) fn handle(
    mut commands: Commands,
    mut my_games_call_tasks: Query<(Entity, &mut MyGamesCall)>,
    mut rtdmenu: ResMut<RTDMenu>,
    mut console: EventWriter<PrintConsoleLine>,
) {
    if my_games_call_tasks.is_empty() {
        return;
    }

    let (entity, mut task) = my_games_call_tasks.single_mut();
    if let Some(my_games_call_response) = future::block_on(future::poll_once(&mut task.0)) {
        rtdmenu.waiting_for_my_games_call = false;
        match my_games_call_response.my_games {
            ResponseMyGames::Valid(res) => rtdmenu.my_games = res,
            ResponseMyGames::Error(error) => {
                console.send(PrintConsoleLine::new(
                    format!("Fetching own games failed, got error: '{}'", error).into(),
                ));
            }
        }

        // Remove the task, since it's done now
        commands.entity(entity).remove::<MyGamesCall>();
        commands.entity(entity).despawn_recursive();
    }
}