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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Workflow Definition
use crate::{
  common::{
    Icon, Identifier, NotificationHook, NotificationWithoutCondition, Parameter, ParameterType,
    Right, StartParameter, Step,
  },
  SchemaVersion,
};
use schemars::JsonSchema;
use semver::Version;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(tag = "schema_version")]
/// # Schema of Workflow Definition for Media Cloud AI
pub enum WorkflowDefinition {
  #[serde(rename = "1.8")]
  Version1_8(Version1_8),
  #[serde(rename = "1.9")]
  Version1_9(Version1_9),
  #[serde(rename = "1.10")]
  Version1_10(Version1_10),
  #[serde(rename = "1.11")]
  Version1_11(Version1_11),
}

impl WorkflowDefinition {
  pub fn new(identifier: &str, label: &str) -> Self {
    WorkflowDefinition::Version1_11(Version1_11 {
      common: Common {
        icon: Icon { icon: None },
        identifier: Identifier {
          content: identifier.to_string(),
        },
        label: label.to_string(),
        is_live: false,
        tags: vec![],
        version_major: 0,
        version_minor: 0,
        version_micro: 1,
      },
      notifications: NotificationHooks {
        notification_hooks: vec![],
      },
      parameters: Parameters { parameters: vec![] },
      steps: Steps { steps: vec![] },
      start_parameters: StartParameters {
        start_parameters: vec![],
      },
    })
  }

  pub fn identifier(&self) -> &str {
    &self.get_common().identifier.content
  }

  pub fn label(&self) -> &str {
    &self.get_common().label
  }

  pub fn version(&self) -> Version {
    let common = self.get_common();

    Version::new(
      common.version_major as u64,
      common.version_minor as u64,
      common.version_micro as u64,
    )
  }

  pub fn schema_version(&self) -> SchemaVersion {
    match self {
      WorkflowDefinition::Version1_8(_) => SchemaVersion::_1_8,
      WorkflowDefinition::Version1_9(_) => SchemaVersion::_1_9,
      WorkflowDefinition::Version1_10(_) => SchemaVersion::_1_10,
      WorkflowDefinition::Version1_11(_) => SchemaVersion::_1_11,
    }
  }

  pub fn is_live(&self) -> bool {
    self.get_common().is_live
  }

  pub fn toggle_is_live(&mut self) {
    self.get_mut_common().is_live = !self.get_common().is_live;
  }

  pub fn tags(&self) -> &Vec<String> {
    &self.get_common().tags
  }

  pub fn steps(&self) -> &Vec<Step> {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &workflow.steps.steps,
      WorkflowDefinition::Version1_9(workflow) => &workflow.steps.steps,
      WorkflowDefinition::Version1_10(workflow) => &workflow.steps.steps,
      WorkflowDefinition::Version1_11(workflow) => &workflow.steps.steps,
    }
  }

  pub fn get_mut_steps(&mut self) -> &mut Vec<Step> {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &mut workflow.steps.steps,
      WorkflowDefinition::Version1_9(workflow) => &mut workflow.steps.steps,
      WorkflowDefinition::Version1_10(workflow) => &mut workflow.steps.steps,
      WorkflowDefinition::Version1_11(workflow) => &mut workflow.steps.steps,
    }
  }

  pub fn get_mut_step(&mut self, step_id: u32) -> Option<&mut Step> {
    self
      .get_mut_steps()
      .iter_mut()
      .find(|step| step.id == step_id)
  }

  fn get_common(&self) -> &Common {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &workflow.common,
      WorkflowDefinition::Version1_9(workflow) => &workflow.common,
      WorkflowDefinition::Version1_10(workflow) => &workflow.common,
      WorkflowDefinition::Version1_11(workflow) => &workflow.common,
    }
  }

  fn get_mut_common(&mut self) -> &mut Common {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &mut workflow.common,
      WorkflowDefinition::Version1_9(workflow) => &mut workflow.common,
      WorkflowDefinition::Version1_10(workflow) => &mut workflow.common,
      WorkflowDefinition::Version1_11(workflow) => &mut workflow.common,
    }
  }

  pub fn set_parameter_on_step(
    &mut self,
    step_id: u32,
    field_name: &str,
    new_value: ParameterType,
    is_parameter: bool,
  ) -> bool {
    if let Some(step) = self.get_mut_step(step_id) {
      if is_parameter {
        if let Some(parameter) = step
          .parameters
          .iter_mut()
          .find(|parameter| parameter.id.content == *field_name)
        {
          match &mut parameter.kind {
            ParameterType::ArrayOfStrings { value, .. } => {
              *value = new_value.get_string_array().unwrap_or_default();
            }
            ParameterType::Boolean { value, .. } => {
              *value = new_value.get_bool();
            }
            ParameterType::Integer { value, .. } => {
              *value = new_value.get_integer();
            }
            ParameterType::Number { value, .. } => {
              *value = new_value.get_number();
            }
            ParameterType::Requirements { value, .. } => {
              *value = new_value.get_requirement();
            }
            ParameterType::String { value, .. } | ParameterType::Template { value, .. } => {
              *value = new_value.get_string();
            }
            ParameterType::Extended {
              value: parameter_value,
              ..
            } => {
              if let ParameterType::Extended { value, .. } = new_value {
                *parameter_value = value;
              }
            }
            _ => {}
          }
          true
        } else {
          false
        }
      } else {
        match field_name {
          "name" => step.name = new_value.get_string().unwrap_or_default(),
          "label" => step.label = new_value.get_string().unwrap_or_default(),
          "icon" => {
            if let Ok(icon) = Icon::new(Some(new_value.get_string().unwrap_or_default())) {
              step.icon = icon;
              return true;
            } else {
              return false;
            }
          }
          _ => {}
        }
        true
      }
    } else {
      false
    }
  }

  pub fn set_workflow_property(&mut self, field_name: &str, value: ParameterType) -> bool {
    if field_name == "identifier" {
      self.get_mut_common().identifier.content = value.get_string().unwrap_or_default();
      return true;
    }
    if field_name == "label" {
      self.get_mut_common().label = value.get_string().unwrap_or_default();
      return true;
    }
    if field_name == "tags" {
      self.get_mut_common().tags = value.get_string_array().unwrap_or_default();
      return true;
    }
    false
  }

  pub fn get_start_parameters(&self) -> &Vec<StartParameter> {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_9(workflow) => &workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_10(workflow) => &workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_11(workflow) => &workflow.start_parameters.start_parameters,
    }
  }

  pub fn get_mut_start_parameters(&mut self) -> &mut Vec<StartParameter> {
    match self {
      WorkflowDefinition::Version1_8(workflow) => &mut workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_9(workflow) => &mut workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_10(workflow) => &mut workflow.start_parameters.start_parameters,
      WorkflowDefinition::Version1_11(workflow) => &mut workflow.start_parameters.start_parameters,
    }
  }

  pub fn get_notification_hooks(&self) -> Option<&Vec<NotificationHook>> {
    match self {
      WorkflowDefinition::Version1_8(_workflow) => None,
      WorkflowDefinition::Version1_9(_workflow) => None,
      WorkflowDefinition::Version1_10(_workflow) => None,
      WorkflowDefinition::Version1_11(workflow) => Some(&workflow.notifications.notification_hooks),
    }
  }

  pub fn get_mut_notification_hooks(&mut self) -> Option<&mut Vec<NotificationHook>> {
    match self {
      WorkflowDefinition::Version1_8(_workflow) => None,
      WorkflowDefinition::Version1_9(_workflow) => None,
      WorkflowDefinition::Version1_10(_workflow) => None,
      WorkflowDefinition::Version1_11(workflow) => {
        Some(&mut workflow.notifications.notification_hooks)
      }
    }
  }
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Version1_8 {
  #[serde(flatten)]
  pub common: Common,
  #[serde(flatten)]
  pub parameters: Parameters,
  #[serde(flatten)]
  pub rights: Rights,
  #[serde(flatten)]
  pub steps: Steps,
  #[serde(flatten)]
  pub start_parameters: StartParameters,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Version1_9 {
  #[serde(flatten)]
  pub common: Common,
  #[serde(flatten)]
  pub parameters: Parameters,
  #[serde(flatten)]
  pub steps: Steps,
  #[serde(flatten)]
  pub start_parameters: StartParameters,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Version1_10 {
  #[serde(flatten)]
  pub common: Common,
  #[serde(flatten)]
  pub notifications: NotificationsWithoutCondition,
  #[serde(flatten)]
  pub parameters: Parameters,
  #[serde(flatten)]
  pub steps: Steps,
  #[serde(flatten)]
  pub start_parameters: StartParameters,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Version1_11 {
  #[serde(flatten)]
  pub common: Common,
  #[serde(flatten)]
  pub notifications: NotificationHooks,
  #[serde(flatten)]
  pub parameters: Parameters,
  #[serde(flatten)]
  pub steps: Steps,
  #[serde(flatten)]
  pub start_parameters: StartParameters,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct Common {
  /// The icon used with the label. One of [theses](https://material.io/resources/icons/) icons.
  pub icon: Icon,
  /// The Identifier of the workflow, used to reference it
  pub identifier: Identifier,
  /// The label of the workflow, used as displayed name
  pub label: String,
  /// Mentions if it defines a live workflow
  #[serde(default, skip_serializing_if = "crate::is_false")]
  pub is_live: bool,
  /// List of tags to classify the worklow
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub tags: Vec<String>,
  /// Major version of this Workflow definition
  pub version_major: u32,
  /// Minor version of this Workflow definition
  pub version_minor: u32,
  /// Micro version of this Workflow definition
  pub version_micro: u32,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct NotificationsWithoutCondition {
  /// Define Notifications got this workflow (default: [])
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub notification_hooks: Vec<NotificationWithoutCondition>,
}

#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct NotificationHooks {
  /// Define Notifications got this workflow (default: [])
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub notification_hooks: Vec<NotificationHook>,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct Rights {
  /// Defines rights for this definition
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub rights: Vec<Right>,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct Parameters {
  /// Storage of dynamic parameters during process of the workflow instance
  pub parameters: Vec<Parameter>,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct StartParameters {
  /// Definition of available parameters to start the workflow definition
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub start_parameters: Vec<StartParameter>,
}

#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct Steps {
  /// Defines rights for this definition
  pub steps: Vec<Step>,
}

#[cfg(test)]
mod tests {
  use super::WorkflowDefinition;

  #[test]
  fn load_version_1_8() {
    let str_workflow_definition =
      include_str!("../tests/resources/workflow_definitions/1.8/simple.json");
    let _: WorkflowDefinition = serde_json::from_str(str_workflow_definition).unwrap();

    let str_workflow_definition =
      include_str!("../tests/resources/workflow_definitions/1.8/transfer.json");
    let _: WorkflowDefinition = serde_json::from_str(str_workflow_definition).unwrap();
  }

  #[test]
  fn load_version_1_9() {
    let str_workflow_definition =
      include_str!("../tests/resources/workflow_definitions/1.9/objet_detection.json");
    let _: WorkflowDefinition = serde_json::from_str(str_workflow_definition).unwrap();
  }

  #[test]
  fn load_version_1_10() {
    let str_workflow_definition =
      include_str!("../tests/resources/workflow_definitions/1.10/simple.json");
    let _: WorkflowDefinition = serde_json::from_str(str_workflow_definition).unwrap();
  }
}