use crate::{
    simulation::{environment::ObservableEnvironment, SimulationEnvironment},
    types::{NodeId, RailwayObjectId},
};
use std::any::Any;
use super::{DecisionAgent, RailMovableAction};
use std::time::Duration;
#[derive(Debug, Default)]
pub struct ForwardUntilTargetAgent {
    object_id: RailwayObjectId,
    position: Option<NodeId>,
    target: Option<NodeId>,
}
impl ForwardUntilTargetAgent {
    pub fn new(object_id: RailwayObjectId) -> Self {
        Self {
            object_id,
            ..Default::default()
        }
    }
    fn target_reached(&self) -> bool {
        self.position == self.target
    }
}
impl DecisionAgent for ForwardUntilTargetAgent {
    type A = RailMovableAction;
    fn next_action(&self, _delta_time: Option<Duration>) -> Self::A {
        if self.target_reached() {
            RailMovableAction::Stop
        } else {
            RailMovableAction::AccelerateForward { acceleration: 20 }
        }
    }
    fn observe(&mut self, environment: &SimulationEnvironment) {
        if let Some(object) = environment
            .get_objects()
            .iter()
            .find(|o| o.id() == self.object_id)
        {
            self.position = object.position();
            self.target = object.next_target();
        }
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}
#[cfg(test)]
mod tests {
    use geo::coord;
    use std::collections::VecDeque;
    use super::*;
    use crate::railway_objects::{RailwayObject, Train};
    #[test]
    fn test_decision_agent() {
        let mut train = Train {
            id: 1,
            position: Some(3),
            geo_location: Some(coord! { x:0.0, y: 0.0}),
            next_target: Some(5),
            targets: VecDeque::from(vec![5, 10, 15]),
            ..Default::default()
        };
        let mut agent = ForwardUntilTargetAgent::new(train.id());
        agent.position = Some(0);
        agent.target = Some(5);
        assert_eq!(
            agent.next_action(None),
            RailMovableAction::AccelerateForward { acceleration: 20 }
        );
        train.position = Some(5);
        let agent = ForwardUntilTargetAgent::new(train.id());
        assert_eq!(agent.next_action(None), RailMovableAction::Stop);
    }
}