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
use crate::dsl::{DivoomDslOperation, DivoomDslParser, DivoomDslRunner};
use crate::schedule::schedule_config::*;
use crate::{DivoomAPIResult, PixooClient};
use log::error;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use tokio_cron_scheduler::{Job, JobScheduler};

#[cfg(feature = "animation-builder")]
use crate::DivoomAnimationTemplateManager;

pub struct DivoomScheduledJob {
    cron: String,
    operations: Vec<DivoomDslOperation>,
}

pub struct DivoomScheduleManager {
    device_address: String,
    jobs: Vec<Arc<DivoomScheduledJob>>,
    job_scheduler: JobScheduler,

    #[cfg(feature = "animation-builder")]
    template_manager: Arc<DivoomAnimationTemplateManager>,
}

impl DivoomScheduleManager {
    #[cfg(feature = "animation-builder")]
    pub fn from_config(
        device_address: String,
        schedules: Vec<DivoomScheduleConfigCronJob>,
        template_manager: Arc<DivoomAnimationTemplateManager>,
    ) -> DivoomAPIResult<Self> {
        let mut jobs: Vec<Arc<DivoomScheduledJob>> = Vec::new();

        for schedule in schedules {
            let parsed_operations: DivoomAPIResult<Vec<DivoomDslOperation>> = schedule
                .operations
                .iter()
                .map(|x| DivoomDslParser::parse(x))
                .collect();
            jobs.push(Arc::new(DivoomScheduledJob {
                cron: schedule.cron,
                operations: parsed_operations?,
            }));
        }

        Ok(DivoomScheduleManager {
            device_address,
            jobs,
            job_scheduler: JobScheduler::new().unwrap(),
            template_manager,
        })
    }

    #[cfg(feature = "animation-builder")]
    pub fn start(&mut self) {
        for job in &self.jobs {
            let cron = job.cron.clone();

            let device_address_for_closure = self.device_address.clone();
            let job_for_closure = job.clone();
            let template_manager_for_closure = self.template_manager.clone();

            let job_closure = move |_, _| -> Pin<Box<dyn Future<Output = ()> + Send>> {
                let device_address_for_async = device_address_for_closure.clone();
                let job_for_async = job_for_closure.clone();
                let template_manager_for_async = template_manager_for_closure.clone();
                Box::pin(async move {
                    let pixoo = match PixooClient::new(&device_address_for_async) {
                        Err(e) => {
                            error!(
                                "Failing to create device client: DeviceAddress = {}, Error = {:?}",
                                &device_address_for_async, e
                            );
                            return;
                        }
                        Ok(v) => v,
                    };

                    let mut dsl_runner = DivoomDslRunner::new(&pixoo, template_manager_for_async);
                    if let Err(e) = dsl_runner.batch_operations(&job_for_async.operations).await {
                        error!("Failing to batch operations: Error = {:?}", e);
                        return;
                    }

                    if let Err(e) = dsl_runner.execute().await {
                        error!("Failing to execute all operations: Error = {:?}", e);
                    }
                })
            };

            self.job_scheduler
                .add(Job::new_async(cron.as_ref(), job_closure).unwrap())
                .unwrap();
        }

        self.job_scheduler.start().unwrap();
    }

    #[cfg(not(feature = "animation-builder"))]
    pub fn from_config(
        device_address: String,
        schedules: Vec<DivoomScheduleConfigCronJob>,
    ) -> DivoomAPIResult<Self> {
        let mut jobs: Vec<Arc<DivoomScheduledJob>> = Vec::new();

        for schedule in schedules {
            let parsed_operations: DivoomAPIResult<Vec<DivoomDslOperation>> = schedule
                .operations
                .iter()
                .map(|x| DivoomDslParser::parse(x))
                .collect();
            jobs.push(Arc::new(DivoomScheduledJob {
                cron: schedule.cron,
                operations: parsed_operations?,
            }));
        }

        Ok(DivoomScheduleManager {
            device_address,
            jobs,
            job_scheduler: JobScheduler::new().unwrap(),
        })
    }

    #[cfg(not(feature = "animation-builder"))]
    pub fn start(&mut self) {
        for job in &self.jobs {
            let cron = job.cron.clone();

            let device_address_for_closure = self.device_address.clone();
            let job_for_closure = job.clone();

            let job_closure = move |_, _| -> Pin<Box<dyn Future<Output = ()> + Send>> {
                let device_address_for_async = device_address_for_closure.clone();
                let job_for_async = job_for_closure.clone();
                Box::pin(async move {
                    let pixoo = match PixooClient::new(&device_address_for_async) {
                        Err(e) => {
                            error!(
                                "Failing to create device client: DeviceAddress = {}, Error = {:?}",
                                &device_address_for_async, e
                            );
                            return;
                        }
                        Ok(v) => v,
                    };

                    let mut dsl_runner = DivoomDslRunner::new(&pixoo);
                    if let Err(e) = dsl_runner.batch_operations(&job_for_async.operations).await {
                        error!("Failing to batch operations: Error = {:?}", e);
                        return;
                    }

                    if let Err(e) = dsl_runner.execute().await {
                        error!("Failing to execute all operations: Error = {:?}", e);
                    }
                })
            };

            self.job_scheduler
                .add(Job::new_async(cron.as_ref(), job_closure).unwrap())
                .unwrap();
        }

        self.job_scheduler.start().unwrap();
    }
}