outfly/src/chat.rs

89 lines
2.4 KiB
Rust
Raw Normal View History

2024-04-12 19:26:23 +00:00
extern crate yaml_rust;
use bevy::prelude::*;
2024-04-12 21:03:46 +00:00
use yaml_rust::{Yaml, YamlLoader};
use crate::{audio};
2024-04-12 19:34:55 +00:00
pub const CHATS: &[&str] = &[
include_str!("chats/serenity.yaml"),
include_str!("chats/startrans.yaml"),
];
2024-04-12 21:03:46 +00:00
pub const TOKEN_CHAT: &str = "chat";
pub struct ChatPlugin;
impl Plugin for ChatPlugin {
fn build(&self, app: &mut App) {
2024-04-12 19:26:23 +00:00
app.add_systems(Startup, load_chats);
2024-04-12 21:03:46 +00:00
app.add_systems(Update, (
handle_new_conversations,
));
app.add_event::<StartConversationEvent>();
2024-04-12 19:34:55 +00:00
app.insert_resource(ChatDB(Vec::new()));
}
}
2024-04-12 21:03:46 +00:00
#[derive(Resource)]
pub struct ChatDB(Vec<Yaml>);
impl ChatDB {
pub fn get_chat_by_id(&self, id: &String) -> Result<u32, String> {
let mut found: Option<u32> = None;
for (index, object_yaml) in self.0.iter().enumerate() {
2024-04-12 21:18:07 +00:00
if let Some(chat_id) = object_yaml[0][TOKEN_CHAT].as_str() {
if chat_id == id {
if found.is_some() {
return Err("Found multiple chats with the same id!".to_string());
}
found = Some(index as u32);
}
2024-04-12 21:03:46 +00:00
}
}
if let Some(result) = found {
return Ok(result);
}
return Err(format!("No chat with the conversation ID `{id}` was found."));
}
}
#[derive(Component)]
#[derive(Clone)]
pub struct Talker {
pub conv_id: String,
2024-04-12 21:03:46 +00:00
pub name: Option<String>,
pub pronoun: Option<String>,
}
#[derive(Event)]
pub struct StartConversationEvent {
pub talker: Talker,
}
2024-04-12 19:26:23 +00:00
2024-04-12 19:34:55 +00:00
pub fn load_chats(mut chatdb: ResMut<ChatDB>) {
for chat_yaml in CHATS {
2024-04-12 21:03:46 +00:00
if let Ok(mut yaml_data) = YamlLoader::load_from_str(chat_yaml) {
2024-04-12 19:34:55 +00:00
chatdb.0.append(&mut yaml_data);
} else {
error!("Could not load chat definitions. Validate files in `src/chats/` path.");
}
2024-04-12 19:26:23 +00:00
}
}
2024-04-12 21:03:46 +00:00
pub fn handle_new_conversations(
//mut commands: Commands,
mut er_conv: EventReader<StartConversationEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
chatdb: Res<ChatDB>,
//time: Res<Time>,
) {
for event in er_conv.read() {
match (*chatdb).get_chat_by_id(&event.talker.conv_id) {
Ok(chat_id) => {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Ping));
dbg!(chat_id);
}
Err(error) => {
error!("Error while looking for chat ID: {error}");
}
}
}
}