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
//!
//! Content validation.
//!

use std::convert::TryFrom;
use std::fmt::{Display, Formatter};

use crate::condition::Condition;
use crate::text::TextTag;
use crate::{CellRef, OdsError};
use std::str::from_utf8;

/// This defines how lists of entries are displayed to the user.
#[derive(Copy, Clone, Debug, Default)]
pub enum ValidationDisplay {
    /// Don't show.
    NoDisplay,
    /// Show the entries in the original order.
    #[default]
    Unsorted,
    /// Sort the entries.
    SortAscending,
}

impl TryFrom<&str> for ValidationDisplay {
    type Error = OdsError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "unsorted" => Ok(ValidationDisplay::Unsorted),
            "sort-ascending" => Ok(ValidationDisplay::SortAscending),
            "none" => Ok(ValidationDisplay::NoDisplay),
            _ => Err(OdsError::Parse(
                "invalid table:display-list ",
                Some(value.to_string()),
            )),
        }
    }
}

impl TryFrom<&[u8]> for ValidationDisplay {
    type Error = OdsError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        match value {
            b"unsorted" => Ok(ValidationDisplay::Unsorted),
            b"sort-ascending" => Ok(ValidationDisplay::SortAscending),
            b"none" => Ok(ValidationDisplay::NoDisplay),
            _ => Err(OdsError::Parse(
                "invalid table:display-list ",
                Some(from_utf8(value)?.into()),
            )),
        }
    }
}

/// Help text for a validation.
#[derive(Clone, Debug)]
pub struct ValidationHelp {
    display: bool,
    title: Option<String>,
    text: Option<Box<TextTag>>,
}

impl Default for ValidationHelp {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationHelp {
    /// Empty message.
    pub fn new() -> Self {
        Self {
            display: true,
            title: None,
            text: None,
        }
    }

    /// Show the help text.
    pub fn set_display(&mut self, display: bool) {
        self.display = display;
    }

    /// Show the help text.
    pub fn display(&self) -> bool {
        self.display
    }

    /// Title for the help text.
    pub fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    /// Title for the help text.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Help text as formatted text.
    pub fn set_text(&mut self, text: Option<TextTag>) {
        if let Some(txt) = text {
            self.text = Some(Box::new(txt));
        } else {
            self.text = None;
        };
    }

    /// Help text as formatted text.
    pub fn text(&self) -> Option<&TextTag> {
        self.text.as_deref()
    }
}

/// Determines the severity of a validation error.
/// When this is error the entered value is discarded, otherwise
/// the error is just shown as a warning or a hint.
#[derive(Copy, Clone, Debug)]
pub enum MessageType {
    /// Hard error.
    Error,
    /// Warning.
    Warning,
    /// Informational.
    Info,
}

impl Display for MessageType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            MessageType::Error => write!(f, "stop"),
            MessageType::Warning => write!(f, "warning"),
            MessageType::Info => write!(f, "information"),
        }
    }
}

/// Error handling for content validations.
#[derive(Clone, Debug)]
pub struct ValidationError {
    display: bool,
    msg_type: MessageType,
    title: Option<String>,
    text: Option<Box<TextTag>>,
}

impl Default for ValidationError {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationError {
    /// Empty message.
    pub fn new() -> Self {
        Self {
            display: true,
            msg_type: MessageType::Error,
            title: None,
            text: None,
        }
    }

    /// Is the error text shown.
    pub fn set_display(&mut self, display: bool) {
        self.display = display;
    }

    /// Is the error text shown.
    pub fn display(&self) -> bool {
        self.display
    }

    /// Type of error.
    pub fn set_msg_type(&mut self, msg_type: MessageType) {
        self.msg_type = msg_type;
    }

    /// Type of error.
    pub fn msg_type(&self) -> &MessageType {
        &self.msg_type
    }

    /// Title for the message.
    pub fn set_title(&mut self, title: Option<String>) {
        self.title = title;
    }

    /// Title for the message.
    pub fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    /// Styled text for the message.
    pub fn set_text(&mut self, text: Option<TextTag>) {
        if let Some(txt) = text {
            self.text = Some(Box::new(txt));
        } else {
            self.text = None;
        };
    }

    /// Styled text for the message.
    pub fn text(&self) -> Option<&TextTag> {
        self.text.as_deref()
    }
}

style_ref!(ValidationRef);

/// Cell content validations.
///
/// This defines a validity constraint via the contained condition.
/// It can be applied to a cell by setting the validation name.
#[derive(Clone, Debug, Default)]
pub struct Validation {
    name: String,
    condition: String,
    base_cell: CellRef,
    allow_empty: bool,
    display_list: ValidationDisplay,
    err: Option<ValidationError>,
    help: Option<ValidationHelp>,
}

impl Validation {
    /// Empty validation.
    pub fn new() -> Self {
        Self {
            name: "".to_string(),
            condition: "".to_string(),
            base_cell: CellRef::new(),
            allow_empty: true,
            display_list: Default::default(),
            err: Some(ValidationError {
                display: true,
                msg_type: MessageType::Error,
                title: None,
                text: None,
            }),
            help: None,
        }
    }

    /// Validation name.
    pub fn set_name<S: Into<String>>(&mut self, name: S) {
        self.name = name.into();
    }

    /// Validation name.
    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    /// Creates a reference struct for this one.
    pub fn validation_ref(&self) -> ValidationRef {
        ValidationRef::from(self.name.clone())
    }

    /// Sets the condition that is checked for new values.
    pub fn set_condition(&mut self, cond: Condition) {
        self.condition = cond.to_string();
    }

    /// Condition for new values.
    pub fn condition(&self) -> &str {
        self.condition.as_str()
    }

    /// Base-cell for the validation. Relative CellReferences in the
    /// condition are relative to this cell. They are moved with the
    /// actual cell this condition is applied to.
    pub fn set_base_cell(&mut self, base: CellRef) {
        self.base_cell = base;
    }

    /// Base-cell for the validation.
    pub fn base_cell(&self) -> &CellRef {
        &self.base_cell
    }

    /// Empty ok?
    pub fn set_allow_empty(&mut self, allow: bool) {
        self.allow_empty = allow;
    }

    /// Empty ok?
    pub fn allow_empty(&self) -> bool {
        self.allow_empty
    }

    /// Display list of choices.
    pub fn set_display(&mut self, display: ValidationDisplay) {
        self.display_list = display;
    }

    /// Display list of choices.
    pub fn display(&self) -> ValidationDisplay {
        self.display_list
    }

    /// Error message.
    pub fn set_err(&mut self, err: Option<ValidationError>) {
        self.err = err;
    }

    /// Error message.
    pub fn err(&self) -> Option<&ValidationError> {
        self.err.as_ref()
    }

    /// Help message.
    pub fn set_help(&mut self, help: Option<ValidationHelp>) {
        self.help = help;
    }

    /// Help message.
    pub fn help(&self) -> Option<&ValidationHelp> {
        self.help.as_ref()
    }
}