1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use std::{
    sync::{Arc, LazyLock},
    time::{Duration, SystemTime},
};

use async_trait::async_trait;
use nalgebra::{Isometry2, Isometry3};

use crate::{
    error::Error,
    gamepad::GamepadEvent,
    traits::{
        BaseVelocity, Gamepad, JointTrajectoryClient, Localization, MoveBase, Navigation, Speaker,
        TrajectoryPoint, TransformResolver,
    },
    waits::WaitFuture,
};

#[allow(clippy::type_complexity)]
#[derive(Debug)]
pub struct Lazy<'a, T> {
    inner: LazyLock<
        Result<T, Arc<Error>>,
        Box<dyn FnOnce() -> Result<T, Arc<Error>> + Send + Sync + 'a>,
    >,
    joint_names: Option<Vec<String>>,
}

impl<'a, T> Lazy<'a, T> {
    /// Creates a new `Lazy` with the given constructor.
    pub fn new(constructor: impl FnOnce() -> Result<T, Error> + Send + Sync + 'a) -> Self {
        Self {
            inner: LazyLock::new(Box::new(|| constructor().map_err(Arc::new))),
            joint_names: None,
        }
    }

    /// Creates a new `Lazy` with the given constructor and joint names.
    ///
    /// The specified joint names will be used as the return value of
    /// `JointTrajectoryClient::joint_names`.
    pub fn with_joint_names(
        constructor: impl FnOnce() -> Result<T, Error> + Send + Sync + 'a,
        joint_names: Vec<String>,
    ) -> Self {
        Self {
            inner: LazyLock::new(Box::new(|| constructor().map_err(Arc::new))),
            joint_names: Some(joint_names),
        }
    }

    /// Returns a reference to the underlying value.
    ///
    /// - If this lazy value has not been constructed yet, this method will construct it.
    /// - If the constructor of this lazy value fails, this method returns an error.
    pub fn get_ref(&self) -> Result<&T, Error> {
        self.inner.as_ref().map_err(|e| Error::Lazy(e.clone()))
    }
}

impl<T> JointTrajectoryClient for Lazy<'_, T>
where
    T: JointTrajectoryClient,
{
    fn joint_names(&self) -> Vec<String> {
        if let Some(joint_names) = &self.joint_names {
            return joint_names.clone();
        }
        match self.get_ref() {
            Ok(this) => this.joint_names(),
            Err(e) => panic!("{e}"),
        }
    }

    fn current_joint_positions(&self) -> Result<Vec<f64>, Error> {
        self.get_ref()?.current_joint_positions()
    }

    fn send_joint_positions(
        &self,
        positions: Vec<f64>,
        duration: Duration,
    ) -> Result<WaitFuture, Error> {
        self.get_ref()?.send_joint_positions(positions, duration)
    }

    fn send_joint_trajectory(&self, trajectory: Vec<TrajectoryPoint>) -> Result<WaitFuture, Error> {
        self.get_ref()?.send_joint_trajectory(trajectory)
    }
}

impl<T> Localization for Lazy<'_, T>
where
    T: Localization,
{
    fn current_pose(&self, frame_id: &str) -> Result<Isometry2<f64>, Error> {
        self.get_ref()?.current_pose(frame_id)
    }
}

impl<T> MoveBase for Lazy<'_, T>
where
    T: MoveBase,
{
    fn current_velocity(&self) -> Result<BaseVelocity, Error> {
        self.get_ref()?.current_velocity()
    }

    fn send_velocity(&self, velocity: &BaseVelocity) -> Result<(), Error> {
        self.get_ref()?.send_velocity(velocity)
    }
}

impl<T> Navigation for Lazy<'_, T>
where
    T: Navigation,
{
    fn send_goal_pose(
        &self,
        goal: Isometry2<f64>,
        frame_id: &str,
        timeout: Duration,
    ) -> Result<WaitFuture, Error> {
        self.get_ref()?.send_goal_pose(goal, frame_id, timeout)
    }

    fn cancel(&self) -> Result<(), Error> {
        self.get_ref()?.cancel()
    }
}

impl<T> Speaker for Lazy<'_, T>
where
    T: Speaker,
{
    fn speak(&self, message: &str) -> Result<WaitFuture, Error> {
        self.get_ref()?.speak(message)
    }
}

impl<T> TransformResolver for Lazy<'_, T>
where
    T: TransformResolver,
{
    fn resolve_transformation(
        &self,
        from: &str,
        to: &str,
        time: SystemTime,
    ) -> Result<Isometry3<f64>, Error> {
        self.get_ref()?.resolve_transformation(from, to, time)
    }
}

#[async_trait]
impl<T> Gamepad for Lazy<'_, T>
where
    T: Gamepad,
{
    async fn next_event(&self) -> GamepadEvent {
        match self.get_ref() {
            Ok(this) => this.next_event().await,
            Err(e) => panic!("{e}"),
        }
    }

    fn stop(&self) {
        match self.get_ref() {
            Ok(this) => this.stop(),
            Err(e) => panic!("{e}"),
        }
    }
}