/*
* 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::ResponseAllForming},
cfg::{CfgDev, CfgUser},
runtime::menu::RTDMenu,
};
use super::AllFormingEvent;
struct AllFormingCallResponse {
all_forming: ResponseAllForming,
}
#[derive(Component)]
pub(super) struct AllFormingCall(Task<AllFormingCallResponse>);
pub(super) fn start(
mut events: EventReader<AllFormingEvent>,
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 all_forming_response = api::game::all_forming(api_address, token);
AllFormingCallResponse {
all_forming: all_forming_response,
}
});
commands.spawn(AllFormingCall(task));
rtdmenu.waiting_for_all_forming_call = true;
}
}
pub(super) fn handle(
mut commands: Commands,
mut all_forming_call_tasks: Query<(Entity, &mut AllFormingCall)>,
mut rtdmenu: ResMut<RTDMenu>,
mut console: EventWriter<PrintConsoleLine>,
) {
if all_forming_call_tasks.is_empty() {
return;
}
let (entity, mut task) = all_forming_call_tasks.single_mut();
if let Some(all_forming_call_response) = future::block_on(future::poll_once(&mut task.0)) {
rtdmenu.waiting_for_all_forming_call = false;
match all_forming_call_response.all_forming {
ResponseAllForming::Valid(res) => rtdmenu.all_forming_games = res,
ResponseAllForming::Error(error) => {
console.send(PrintConsoleLine::new(
format!("Fetching all forming games failed, got error: '{}'", error).into(),
));
}
}
// Remove the task, since it's done now
commands.entity(entity).remove::<AllFormingCall>();
commands.entity(entity).despawn_recursive();
}
}