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
//! # Data transfer objects for FEEL values

use crate::context::FeelContext;
use crate::errors::*;
use crate::values::Value;
use crate::{value_null, Name};
use dmntk_common::DmntkError;
use serde::{Deserialize, Serialize};

pub const XSD_STRING: &str = "xsd:string";
pub const XSD_INTEGER: &str = "xsd:integer";
pub const XSD_DECIMAL: &str = "xsd:decimal";
pub const XSD_DOUBLE: &str = "xsd:double";
pub const XSD_BOOLEAN: &str = "xsd:boolean";
pub const XSD_DATE: &str = "xsd:date";
pub const XSD_DATE_TIME: &str = "xsd:dateTime";
pub const XSD_TIME: &str = "xsd:time";
pub const XSD_DURATION: &str = "xsd:duration";

/// Type alias for an object value represented as a vector of components.
type ObjectDto = Vec<ComponentDto>;

/// DTO representing a single FEEL value.
#[derive(Default, Serialize, Deserialize)]
pub struct ValueDto {
  /// Simple value.
  #[serde(rename = "simple")]
  simple: Option<SimpleDto>,
  /// Object value.
  #[serde(rename = "components")]
  object: Option<ObjectDto>,
  /// List value.
  #[serde(rename = "list")]
  list: Option<ListDto>,
}

/// DTO representing a simple value.
#[derive(Default, Serialize, Deserialize)]
pub struct SimpleDto {
  /// Name of the value's type.
  #[serde(rename = "type")]
  typ: Option<String>,
  /// Value represented as text.
  #[serde(rename = "text")]
  text: Option<String>,
  /// Flag indicating if the value is `nil`.
  #[serde(rename = "isNil")]
  nil: bool,
}

impl SimpleDto {
  /// Creates a [SimpleDto] with initial type and value.
  fn new(typ: &str, text: String) -> Option<Self> {
    Some(Self {
      typ: Some(typ.to_string()),
      text: Some(text),
      nil: false,
    })
  }

  /// Creates a [SimpleDto] with `nil` value.
  fn new_nil() -> Option<Self> {
    Some(Self { typ: None, text: None, nil: true })
  }
}

/// DTO representing a component of the object value.
#[derive(Default, Serialize, Deserialize)]
pub struct ComponentDto {
  /// Name of the value's component.
  #[serde(rename = "name")]
  name: Option<String>,
  /// Value of the component.
  #[serde(rename = "value")]
  value: Option<ValueDto>,
  /// Flag indicating if the value of the component is `nil`.
  #[serde(rename = "isNil")]
  nil: bool,
}

/// DTO representing a list of values.
#[derive(Default, Serialize, Deserialize)]
pub struct ListDto {
  /// Items in the list ov values.
  #[serde(rename = "items")]
  items: Vec<ValueDto>,
  /// Flag indicating if the value is of the list is `nil`.
  #[serde(rename = "isNil")]
  nil: bool,
}

impl ListDto {
  /// Creates a [ListDto] with initial items.
  fn new(items: Vec<ValueDto>) -> Option<Self> {
    Some(Self { items, nil: false })
  }
}

impl TryFrom<&Value> for ValueDto {
  type Error = DmntkError;
  /// Converts a [Value] to [ValueDto].
  fn try_from(value: &Value) -> Result<Self, Self::Error> {
    match value {
      Value::String(inner) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_STRING, inner.to_string()),
        ..Default::default()
      }),
      v @ Value::Number(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_DECIMAL, v.to_string()),
        ..Default::default()
      }),
      v @ Value::Boolean(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_BOOLEAN, v.to_string()),
        ..Default::default()
      }),
      v @ Value::Date(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_DATE, v.to_string()),
        ..Default::default()
      }),
      v @ Value::DateTime(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_DATE_TIME, v.to_string()),
        ..Default::default()
      }),
      v @ Value::Time(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_TIME, v.to_string()),
        ..Default::default()
      }),
      v @ Value::YearsAndMonthsDuration(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_DURATION, v.to_string()),
        ..Default::default()
      }),
      v @ Value::DaysAndTimeDuration(_) => Ok(ValueDto {
        simple: SimpleDto::new(XSD_DURATION, v.to_string()),
        ..Default::default()
      }),
      Value::Null(_) => Ok(ValueDto {
        simple: SimpleDto::new_nil(),
        ..Default::default()
      }),
      Value::Context(ctx) => {
        let mut components = vec![];
        for (name, value) in ctx.iter() {
          components.push(ComponentDto {
            name: Some(name.to_string()),
            value: Some(value.try_into()?),
            nil: false,
          });
        }
        Ok(ValueDto {
          object: Some(components),
          ..Default::default()
        })
      }
      Value::List(list) => {
        let mut items = vec![];
        for value in list {
          items.push(value.try_into()?);
        }
        Ok(ValueDto {
          list: ListDto::new(items),
          ..Default::default()
        })
      }
      _ => Ok(Default::default()),
    }
  }
}

impl TryFrom<&ValueDto> for Value {
  type Error = DmntkError;
  /// Converts a [ValueDto] to [Value].
  fn try_from(value: &ValueDto) -> Result<Self, Self::Error> {
    if let Some(value_dto) = &value.simple {
      return Value::try_from(value_dto);
    }
    if let Some(components) = &value.object {
      return Value::try_from(components);
    }
    if let Some(list) = &value.list {
      return Value::try_from(list);
    }
    Err(err_missing_attribute("no 'simple', 'components' or 'list' attribute"))
  }
}

impl TryFrom<&SimpleDto> for Value {
  type Error = DmntkError;
  /// Converts [SimpleDto] into [Value].
  fn try_from(value: &SimpleDto) -> Result<Self, Self::Error> {
    if value.nil {
      return Ok(value_null!());
    }
    if let Some(typ) = &value.typ {
      if let Some(text) = &value.text {
        return match typ.as_str() {
          XSD_STRING => Ok(Value::String(text.clone())),
          XSD_INTEGER => Ok(Value::try_from_xsd_integer(text)?),
          XSD_DECIMAL => Ok(Value::try_from_xsd_decimal(text)?),
          XSD_DOUBLE => Ok(Value::try_from_xsd_double(text)?),
          XSD_BOOLEAN => Ok(Value::try_from_xsd_boolean(text)?),
          XSD_DATE => Ok(Value::try_from_xsd_date(text)?),
          XSD_TIME => Ok(Value::try_from_xsd_time(text)?),
          XSD_DATE_TIME => Ok(Value::try_from_xsd_date_time(text)?),
          XSD_DURATION => Ok(Value::try_from_xsd_duration(text)?),
          _ => Err(err_invalid_attribute(&format!("invalid type '{typ}'"))),
        };
      } else {
        Err(err_missing_attribute("simple value must have 'text' attribute"))
      }
    } else {
      Err(err_missing_attribute("simple value must have 'type' attribute"))
    }
  }
}

impl TryFrom<&ObjectDto> for Value {
  type Error = DmntkError;
  /// Converts an [ObjectDto] to [Value].
  fn try_from(object: &ObjectDto) -> Result<Self, Self::Error> {
    let mut ctx: FeelContext = Default::default();
    for item in object {
      let item_name = item.name.as_ref().ok_or_else(|| err_invalid_attribute("component must have a name"))?.to_string();
      let value = Value::try_from(item)?;
      let key: Name = item_name.into();
      ctx.set_entry(&key, value);
    }
    Ok(ctx.into())
  }
}

impl TryFrom<&ComponentDto> for Value {
  type Error = DmntkError;
  /// Converts a [ComponentDto] to [Value].
  fn try_from(value: &ComponentDto) -> Result<Self, Self::Error> {
    if value.nil {
      return Ok(value_null!());
    }
    if let Some(v) = &value.value {
      Value::try_from(v)
    } else {
      Err(err_invalid_attribute("component must have a value"))
    }
  }
}

impl TryFrom<&ListDto> for Value {
  type Error = DmntkError;
  /// Converts a [ListDto] to [Value].
  fn try_from(value: &ListDto) -> Result<Self, Self::Error> {
    if value.nil {
      return Ok(value_null!());
    }
    let mut values = vec![];
    for item in &value.items {
      values.push(Value::try_from(item)?);
    }
    Ok(Value::List(values))
  }
}