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
407
408
409
410
411
412
413
414
415
use std::fmt;

use crate::{
    ConfId, Error, Message, MessageCode, MessageData, MessageType, RequestCode, RequestType,
    Result, UnitNumber,
};

mod stack_status_change;

pub use stack_status_change::*;

/// Represents the additional data in a stack request.
#[repr(C)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StackRequest {
    stack_box: Option<UnitNumber>,
    status_change: Option<StackStatusChange>,
}

impl StackRequest {
    /// Creates a new [StackRequest].
    pub const fn new() -> Self {
        Self {
            stack_box: None,
            status_change: None,
        }
    }

    /// Gets the length of the [StackRequest].
    pub const fn len(&self) -> usize {
        match (self.stack_box, self.status_change) {
            (Some(_sb), None) => UnitNumber::len(),
            (None, Some(_sc)) => 0,
            (Some(_sb), Some(_sc)) => UnitNumber::len() + StackStatusChange::len(),
            _ => 0,
        }
    }

    /// Gets whether the [StackRequest] is empty.
    pub const fn is_empty(&self) -> bool {
        self.stack_box.is_none() && self.status_change.is_none()
    }

    /// Gets the recycler box [UnitNumber] used to stack notes.
    pub const fn stack_box(&self) -> Option<UnitNumber> {
        self.stack_box
    }

    /// Sets the recycler box [UnitNumber] used to stack notes.
    pub fn set_stack_box(&mut self, stack_box: UnitNumber) {
        self.stack_box.replace(stack_box);
    }

    /// Builder function that sets the recycler box [UnitNumber] used to stack notes.
    pub fn with_stack_box(mut self, stack_box: UnitNumber) -> Self {
        self.set_stack_box(stack_box);
        self
    }

    /// Unsets the recycler box [UnitNumber] used to stack notes (use the default box).
    pub fn unset_stack_box(&mut self) -> Option<UnitNumber> {
        self.stack_box.take()
    }

    /// Gets the device [StackStatusChange] after a collection operation.
    pub const fn status_change(&self) -> Option<StackStatusChange> {
        self.status_change
    }

    /// Sets the device [StackStatusChange] after a collection operation.
    pub fn set_status_change(&mut self, status_change: StackStatusChange) {
        self.status_change.replace(status_change);
    }

    /// Builder function that sets the device [StackStatusChange] after a collection operation.
    pub fn with_status_change(mut self, status_change: StackStatusChange) -> Self {
        self.set_status_change(status_change);
        self
    }

    /// Unsets the device [StackStatusChange] after a collection operation (default status change).
    pub fn unset_status_change(&mut self) -> Option<StackStatusChange> {
        self.status_change.take()
    }

    /// Gets the [MessageType] for the [StackRequest].
    pub const fn message_type(&self) -> MessageType {
        MessageType::Request(self.request_type())
    }

    /// Gets the [RequestType] for the [StackRequest].
    pub const fn request_type(&self) -> RequestType {
        RequestType::Operation
    }

    /// Gets the [MessageCode] for the [StackRequest].
    pub const fn message_code(&self) -> MessageCode {
        MessageCode::Request(self.request_code())
    }

    /// Gets the [RequestCode] for the [StackRequest].
    pub const fn request_code(&self) -> RequestCode {
        RequestCode::Stack
    }

    /// Converts a byte buffer into a [StackRequest].
    pub fn from_bytes(buf: &[u8]) -> Result<Self> {
        match buf.len() {
            0 => Ok(Self::new()),
            1 => Ok(Self {
                stack_box: Some(UnitNumber::from_u8(buf[0])),
                status_change: None,
            }),
            _ => Ok(Self {
                stack_box: Some(UnitNumber::from_u8(buf[0])),
                status_change: Some(buf[1].try_into()?),
            }),
        }
    }

    /// Writes the [StackRequest] to a byte buffer.
    pub fn to_bytes(&self, buf: &mut [u8]) -> Result<()> {
        let len = self.len();
        let buf_len = buf.len();

        if buf_len < len {
            Err(Error::InvalidStackRequestLen((buf_len, len)))
        } else {
            match (self.stack_box, self.status_change) {
                (Some(sb), None) if sb.is_valid() => buf[0] = sb.to_u8(),
                (Some(sb), None) if sb.is_empty() => buf[0] = 0,
                (Some(sb), Some(sc)) if sb.is_valid() && sc.is_valid() => {
                    buf[..=1].copy_from_slice(&[sb.to_u8(), sc.to_u8()])
                }
                (Some(sb), Some(sc)) if sb.is_empty() && sc.is_valid() => {
                    buf[..=1].copy_from_slice(&[0, sc.to_u8()])
                }
                _ => (),
            }

            Ok(())
        }
    }

    /// Converts the [StackRequest] to a byte vector.
    pub fn as_bytes(&self) -> Vec<u8> {
        let len = self.len();
        match len {
            0 => Vec::new(),
            _ => {
                let mut out = vec![0u8; len];
                self.to_bytes(&mut out).ok();
                out
            }
        }
    }

    /// Converts the [StackRequest] to a byte vector.
    pub fn into_bytes(self) -> Vec<u8> {
        self.as_bytes()
    }
}

impl From<StackRequest> for MessageData {
    fn from(val: StackRequest) -> Self {
        Self::new()
            .with_conf_id(ConfId::Acceptor)
            .with_message_type(MessageType::Request(RequestType::Operation))
            .with_message_code(MessageCode::Request(RequestCode::Stack))
            .with_additional(val.into_bytes().as_ref())
    }
}

impl From<&StackRequest> for MessageData {
    fn from(val: &StackRequest) -> Self {
        Self::new()
            .with_conf_id(ConfId::Acceptor)
            .with_message_type(MessageType::Request(RequestType::Operation))
            .with_message_code(MessageCode::Request(RequestCode::Stack))
            .with_additional(val.as_bytes().as_ref())
    }
}

impl From<StackRequest> for Message {
    fn from(val: StackRequest) -> Self {
        Self::new().with_data(val.into())
    }
}

impl From<&StackRequest> for Message {
    fn from(val: &StackRequest) -> Self {
        Self::new().with_data(val.into())
    }
}

impl TryFrom<&MessageData> for StackRequest {
    type Error = Error;

    fn try_from(val: &MessageData) -> Result<Self> {
        let exp_type = MessageType::Request(RequestType::Operation);
        let exp_code = MessageCode::Request(RequestCode::Stack);

        let msg_type = val.message_type();
        let msg_code = val.message_code();

        if val.conf_id().is_empty() {
            Err(Error::InvalidConfId(val.conf_id().into()))
        } else if msg_type != exp_type {
            Err(Error::InvalidMessageType(msg_type.into()))
        } else if msg_code != exp_code {
            Err(Error::InvalidMessageCode((
                msg_code.into(),
                exp_code.into(),
            )))
        } else {
            Self::from_bytes(val.additional())
        }
    }
}

impl TryFrom<MessageData> for StackRequest {
    type Error = Error;

    fn try_from(val: MessageData) -> Result<Self> {
        (&val).try_into()
    }
}

impl TryFrom<&Message> for StackRequest {
    type Error = Error;

    fn try_from(val: &Message) -> Result<Self> {
        val.data().try_into()
    }
}

impl TryFrom<Message> for StackRequest {
    type Error = Error;

    fn try_from(val: Message) -> Result<Self> {
        (&val).try_into()
    }
}

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

impl fmt::Display for StackRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{")?;
        write!(f, r#""message_type": {}, "#, self.message_type())?;
        write!(f, r#""message_code": {} "#, self.message_code())?;

        match (self.stack_box.as_ref(), self.status_change.as_ref()) {
            (Some(sb), Some(sc)) => {
                write!(f, r#", "stack_box": {sb}, "#)?;
                write!(f, r#""status_change": {sc}"#)?;
            }
            (Some(sb), None) => {
                write!(f, r#", "stack_box": {sb}"#)?;
            }
            (None, Some(sc)) => {
                write!(f, r#", "status_change": {sc}"#)?;
            }
            _ => (),
        }

        write!(f, "}}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{EventCode, EventType, RequestCode, RequestType};

    #[test]
    fn test_stack_request() -> Result<()> {
        let msg_data = MessageData::new()
            .with_conf_id(ConfId::Acceptor)
            .with_message_type(MessageType::Request(RequestType::Operation))
            .with_message_code(MessageCode::Request(RequestCode::Stack));

        for stat_change in [
            StackStatusChange::Idle.to_u8(),
            StackStatusChange::Inhibit.to_u8(),
        ] {
            for stack_box in 0x0..=0xf {
                let stack_data = msg_data.clone().with_additional(&[stack_box, stat_change]);
                let stack_req = StackRequest::try_from(stack_data)?;

                assert_eq!(stack_req.stack_box(), Some(UnitNumber::from_u8(stack_box)));
                assert_eq!(
                    stack_req.status_change(),
                    Some(StackStatusChange::from_u8(stat_change))
                );
            }
        }

        let stack_req = StackRequest::try_from(msg_data)?;

        assert!(stack_req.stack_box().is_none());
        assert!(stack_req.status_change().is_none());

        Ok(())
    }

    #[test]
    fn test_stack_request_invalid() -> Result<()> {
        let msg_data = MessageData::new()
            .with_conf_id(ConfId::Acceptor)
            .with_message_type(MessageType::Request(RequestType::Operation))
            .with_message_code(MessageCode::Request(RequestCode::Stack));

        for stat_change in 0x2..=0xff {
            for stack_box in 0x0..=0xff {
                let stack_data = msg_data.clone().with_additional(&[stack_box, stat_change]);
                assert!(StackRequest::try_from(stack_data).is_err());
            }
        }

        for msg_type in [MessageType::Reserved]
            .into_iter()
            .chain((0x80..=0x8f).map(|m| MessageType::Event(EventType::from_u8(m))))
            .chain(
                [
                    RequestType::Status,
                    RequestType::SetFeature,
                    RequestType::Reserved,
                ]
                .map(MessageType::Request),
            )
        {
            let stack_data = msg_data.clone().with_message_type(msg_type);
            assert!(
                StackRequest::try_from(stack_data).is_err(),
                "message type: {msg_type}"
            );
        }

        for msg_code in [
            RequestCode::Uid,
            RequestCode::ProgramSignature,
            RequestCode::Version,
            RequestCode::SerialNumber,
            RequestCode::ModelName,
            RequestCode::Status,
            RequestCode::Reset,
            RequestCode::Inhibit,
            RequestCode::Collect,
            RequestCode::Key,
            RequestCode::EventResendInterval,
            RequestCode::Idle,
            RequestCode::Reject,
            RequestCode::Hold,
            RequestCode::AcceptorCollect,
            RequestCode::DenominationDisable,
            RequestCode::DirectionDisable,
            RequestCode::CurrencyAssign,
            RequestCode::CashBoxSize,
            RequestCode::NearFull,
            RequestCode::BarCode,
            RequestCode::Insert,
            RequestCode::ConditionalVend,
            RequestCode::Pause,
            RequestCode::NoteDataInfo,
            RequestCode::RecyclerCollect,
            RequestCode::Reserved,
        ]
        .map(MessageCode::Request)
        .into_iter()
        .chain(
            [
                EventCode::PowerUp,
                EventCode::PowerUpAcceptor,
                EventCode::PowerUpStacker,
                EventCode::Inhibit,
                EventCode::ProgramSignature,
                EventCode::Rejected,
                EventCode::Collected,
                EventCode::Clear,
                EventCode::OperationError,
                EventCode::Failure,
                EventCode::NoteStay,
                EventCode::PowerUpAcceptorAccepting,
                EventCode::PowerUpStackerAccepting,
                EventCode::Idle,
                EventCode::Escrow,
                EventCode::VendValid,
                EventCode::AcceptorRejected,
                EventCode::Returned,
                EventCode::AcceptorCollected,
                EventCode::Insert,
                EventCode::ConditionalVend,
                EventCode::Pause,
                EventCode::Resume,
                EventCode::AcceptorClear,
                EventCode::AcceptorOperationError,
                EventCode::AcceptorFailure,
                EventCode::AcceptorNoteStay,
                EventCode::FunctionAbeyance,
                EventCode::Reserved,
            ]
            .map(MessageCode::Event),
        ) {
            let stack_data = msg_data.clone().with_message_code(msg_code);
            assert!(StackRequest::try_from(stack_data).is_err());
        }

        Ok(())
    }
}