/*
* 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::ResponseCreateGame},
cfg::{CfgDev, CfgUser},
runtime::menu::{PlayMenuUIState, RTDMenu},
};
use super::CreateGameEvent;
struct CreateGameCallResponse {
game: ResponseCreateGame,
}
#[derive(Component)]
pub(super) struct CreateGameCall(Task<CreateGameCallResponse>);
pub(super) fn start(
mut events: EventReader<CreateGameEvent>,
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 create_game_response = api::game::create(api_address, token);
CreateGameCallResponse {
game: create_game_response,
}
});
commands.spawn(CreateGameCall(task));
rtdmenu.waiting_for_create_game_call = true;
}
}
pub(super) fn handle(
mut commands: Commands,
mut create_game_call_tasks: Query<(Entity, &mut CreateGameCall)>,
mut rtdmenu: ResMut<RTDMenu>,
mut console: EventWriter<PrintConsoleLine>,
) {
if create_game_call_tasks.is_empty() {
return;
}
let (entity, mut task) = create_game_call_tasks.single_mut();
if let Some(create_game_call_response) = future::block_on(future::poll_once(&mut task.0)) {
rtdmenu.waiting_for_create_game_call = false;
match create_game_call_response.game {
ResponseCreateGame::Valid(res) => {
rtdmenu.cur_game = Some(res.clone());
rtdmenu.play_menu_ui_state = PlayMenuUIState::InLobbyHost;
console.send(PrintConsoleLine::new(
format!("Created game with id: '{}'", res.id).into(),
));
}
ResponseCreateGame::Error(error) => {
console.send(PrintConsoleLine::new(
format!("Game creation failed, got error: '{}'", error).into(),
));
}
}
// Remove the task, since it's done now
commands.entity(entity).remove::<CreateGameCall>();
commands.entity(entity).despawn_recursive();
}
}