use godot::{classes::Input, prelude::*};

use crate::{consts, core::event_bus::EventBus};

#[derive(GodotClass)]
#[class(base=Node)]
pub struct PlayerInputSystem {
    event_bus: Option<Gd<EventBus>>,
    base: Base<Node>,
}

#[godot_api]
impl INode for PlayerInputSystem {
    fn init(base: Base<Node>) -> Self {
        Self {
            event_bus: None,
            base,
        }
    }

    fn ready(&mut self) {
        self.event_bus = Some(self.base().get_node_as::<EventBus>(consts::EVENT_BUS_PATH));
    }

    fn process(&mut self, delta: f64) {
        let Some(event_bus) = &self.event_bus else {
            return;
        };

        let input = Input::singleton();

        if input.is_action_pressed(consts::LIFT_ACTION) {
            event_bus
                .clone()
                .bind_mut()
                .publish_lift_effort(delta as f32);
        }

        if input.is_action_just_released(consts::LIFT_ACTION) {
            event_bus.clone().bind_mut().publish_focus_released();
        }
    }
}
