/*
* 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 crate::{
plugins::game::GameData, game_status::GameStatus, api::game::Game,
};
use bevy::{prelude::*, tasks::{Task, AsyncComputeTaskPool}};
use futures_lite::future;
#[derive(Component)]
pub struct ParseGameStatus(Task<GameStatus>);
#[derive(Clone)]
pub struct ParseGameStatusEvent {
pub game: Game,
}
pub fn start_call(
mut commands: Commands,
mut start_ev_r: EventReader<ParseGameStatusEvent>,
) {
for ev in start_ev_r.iter() {
let thread_pool = AsyncComputeTaskPool::get();
let ev = ev.clone();
let task = thread_pool.spawn(async move {
let res = GameStatus::new(&ev.game.actions.unwrap());
res
});
commands.spawn(ParseGameStatus(task));
}
}
pub fn handle_call(
mut commands: Commands,
mut tasks: Query<(Entity, &mut ParseGameStatus)>,
mut game_data: ResMut<GameData>,
) {
match tasks.get_single_mut() {
Ok((entity, mut task)) => {
if let Some(response) = future::block_on(future::poll_once(&mut task.0)) {
game_data.game_status = Some(response);
game_data.parsing_data = false;
// remove the task
commands.entity(entity).remove::<ParseGameStatus>();
commands.entity(entity).despawn_recursive();
}
}
// NOTE: don't do anything if the wanted thingy doesn't exist
_ => {}
}
}