//! This example demonstrates how to use the FmodPlugin to play a sound.
//! Make sure to follow the instructions in the README.md to set up the demo project.

use bevy::input::keyboard::KeyboardInput;
use bevy::input::ButtonState;
use bevy::prelude::*;
use bevy_fmod::prelude::AudioSource;
use bevy_fmod::prelude::*;

fn main() {
    App::new()
        .add_plugins((
            DefaultPlugins,
            FmodPlugin {
                audio_banks_paths: &[
                    "./assets/audio/Martian Chess/Build/Desktop/Master.bank",
                    "./assets/audio/Martian Chess/Build/Desktop/Master.strings.bank",
                    "./assets/audio/Martian Chess/Build/Desktop/Music.bank",
                    "./assets/audio/Martian Chess/Build/Desktop/SFX.bank",
                ],
            },
        ))
        .add_systems(Startup, startup)
        .add_systems(Update, play_music)
        .run();
}

#[derive(Component)]
struct MyMusicPlayer;

fn startup(mut commands: Commands, studio: Res<FmodStudio>) {
    commands
        .spawn(NodeBundle {
            style: Style {
                flex_direction: FlexDirection::Column,
                ..default()
            },
            ..default()
        })
        .with_children(|parent| {
            studio
                .0
                .get_bank_list(10)
                .expect("List banks")
                .into_iter()
                .flat_map(|bank| {
                    bank.get_event_list(100)
                        .into_iter()
                        .flat_map(|events| events.into_iter())
                        .filter_map(|event| event.get_path().ok())
                })
                .for_each(|event_path| {
                    parent
                        .spawn((
                            ButtonBundle {
                                style: Style { ..default() },
                                ..default()
                            },
                            AudioSource::new(studio.0.get_event(event_path.as_str()).unwrap()),
                        ))
                        .with_children(|parent| {
                            parent.spawn(TextBundle::from_section(
                                event_path,
                                TextStyle {
                                    color: Color::BLACK.into(),
                                    ..default()
                                },
                            ));
                        });
                });
        });

    commands.spawn((
        Camera2dBundle { ..default() },
        UiCameraConfig { show_ui: true },
    ));
}

fn play_music(
    mut events: Query<
        (&Interaction, &mut AudioSource),
        (Changed<Interaction>, With<Button>, With<AudioSource>),
    >,
) {
    events
        .iter_mut()
        .filter(|(&i, _)| i == Interaction::Pressed)
        .for_each(|(_, a)| {
            info!("Toggling Audio");
            a.play();
        });
}
