use bevy::prelude::*;

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
#[require(Transform)]
pub struct Cash;

#[derive(Component, Reflect, Default)]
#[reflect(Component)]
struct CashText;

#[derive(Resource, Reflect, Default)]
pub struct CashResource {
    pub cash: i32,
}

#[derive(Event)]
pub struct CashCollectEvent;

pub fn plugin(app: &mut App) {
    app.init_resource::<CashResource>();
    app.add_systems(Startup, setup);
    app.add_systems(Update, (rotate, update_ui));
    app.add_observer(on_collect);
}

fn on_collect(
    _trigger: Trigger<CashCollectEvent>,
    mut commands: Commands,
    mut cash: ResMut<CashResource>,
    asset_server: Res<AssetServer>,
) {
    commands.spawn(AudioPlayer::new(asset_server.load("sfx/effects/cash.ogg")));

    cash.cash += 100;
}

fn rotate(time: Res<Time>, mut query: Query<&mut Transform, With<Cash>>) {
    for mut transform in query.iter_mut() {
        transform.rotate(Quat::from_rotation_y(time.delta_secs()));
    }
}

fn update_ui(
    cash: Res<CashResource>,
    text: Query<Entity, With<CashText>>,
    mut writer: TextUiWriter,
) {
    if cash.is_changed() {
        let Some(text) = text.iter().next() else {
            return;
        };

        *writer.text(text, 0) = cash.cash.to_string();
    }
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn((
        Text::new("0"),
        CashText,
        TextFont {
            font: asset_server.load("font.ttf"),
            font_size: 34.0,
            ..default()
        },
        TextColor(Color::Srgba(Srgba::rgb(0., 1., 0.))),
        TextLayout::new_with_justify(JustifyText::Center),
        Node {
            position_type: PositionType::Absolute,
            bottom: Val::Px(40.0),
            left: Val::Px(100.0),
            ..default()
        },
    ));
}
