/*
* This file is part of laurelin/client
* 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::ResponseJoinGame},
cfg::{CfgDev, CfgUser},
runtime::menu::{PlayMenuUIState, RTDMenu},
};
use super::JoinGameEvent;
struct JoinGameCallResponse {
res: ResponseJoinGame,
}
#[derive(Component)]
pub(super) struct JoinGameCall(Task<JoinGameCallResponse>);
pub(super) fn start(
mut events: EventReader<JoinGameEvent>,
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 game_id = rtdmenu.cur_game.as_ref().unwrap().id.clone();
let thread_pool = AsyncComputeTaskPool::get();
let task = thread_pool.spawn(async move {
let join_game_response = api::game::join(api_address, token, game_id);
JoinGameCallResponse {
res: join_game_response,
}
});
commands.spawn(JoinGameCall(task));
rtdmenu.waiting_for_join_game_call = true;
}
}
pub(super) fn handle(
mut commands: Commands,
mut join_game_call_tasks: Query<(Entity, &mut JoinGameCall)>,
mut rtdmenu: ResMut<RTDMenu>,
mut console: EventWriter<PrintConsoleLine>,
) {
if join_game_call_tasks.is_empty() {
return;
}
let (entity, mut task) = join_game_call_tasks.single_mut();
if let Some(join_game_call_response) = future::block_on(future::poll_once(&mut task.0)) {
rtdmenu.waiting_for_join_game_call = false;
match join_game_call_response.res {
ResponseJoinGame::Valid(_res) => {
rtdmenu.play_menu_ui_state = PlayMenuUIState::InLobbyGuest;
console.send(PrintConsoleLine::new(
format!(
"Joined game with id: '{}'",
rtdmenu.cur_game.as_ref().unwrap().id
)
.into(),
));
}
ResponseJoinGame::Error(error) => {
console.send(PrintConsoleLine::new(
format!("Join game failed, got error: '{}'", error).into(),
));
}
}
// Remove the task, since it's done now
commands.entity(entity).remove::<JoinGameCall>();
commands.entity(entity).despawn_recursive();
}
}