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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use super::super::tmch::{
    AddCase, BalanceData, CaseAdd, CaseDocument, CaseDocumentClass, CaseRemove, CheckRequest,
    CheckResponse, CreateLabel, CreateRequest, CreateResponse, Document, DocumentClass, FileType,
    MarkInfoRequest, MarkInfoResponse, MarkLabel, MarkPOUStatus, MarkSMDInfoRequest,
    MarkSMDInfoResponse, MarkStatus, MarkVariation, RenewRequest, RenewResponse, Status,
    TransferInitiateRequest, TransferInitiateResponse, TransferRequest, TransferResponse,
    TrexStatus, UpdateAdd, UpdateRemove, UpdateRequest, UpdateResponse,
};
use super::super::{Error, Period, PeriodUnit, Response};
use super::router::HandleReqReturn;
use super::tmch_proto;
use crate::client::tmch::CaseType;
use std::convert::{TryFrom, TryInto};

pub(crate) fn check_mark_id<T>(id: &str) -> Result<(), Response<T>> {
    lazy_static! {
        static ref RE: regex::Regex = regex::Regex::new("\\d+-\\d+").unwrap();
    }
    if RE.is_match(id) {
        Ok(())
    } else {
        Err(Err(Error::Err("invalid mark_id".to_string())))
    }
}

pub(crate) fn check_case_id<T>(id: &str) -> Result<(), Response<T>> {
    lazy_static! {
        static ref RE: regex::Regex = regex::Regex::new("case-\\d+").unwrap();
    }
    if RE.is_match(id) {
        Ok(())
    } else {
        Err(Err(Error::Err("invalid case_id".to_string())))
    }
}

impl From<&CreateLabel> for tmch_proto::TMCHLabel {
    fn from(from: &CreateLabel) -> Self {
        tmch_proto::TMCHLabel {
            label: from.label.to_string(),
            smd_inclusion: Some(tmch_proto::TMCHNotify {
                value: "".to_string(),
                enable: from.smd_inclusion,
            }),
            claims_notify: Some(tmch_proto::TMCHNotify {
                value: "".to_string(),
                enable: from.smd_inclusion,
            }),
            trex_activate: None,
            trex_renew: None,
        }
    }
}

impl From<&Document> for tmch_proto::TMCHDocument {
    fn from(from: &Document) -> Self {
        tmch_proto::TMCHDocument {
            document_class: match from.class {
                DocumentClass::AssigneeDeclaration => {
                    tmch_proto::TMCHDocumentClass::AssigneeDeclaration
                }
                DocumentClass::LicenseeDeclaration => {
                    tmch_proto::TMCHDocumentClass::LicenseeDeclaration
                }
                DocumentClass::DeclarationProofOfUseOneSample => {
                    tmch_proto::TMCHDocumentClass::DeclarationProofOfUseOneSample
                }
                DocumentClass::OtherProofOfUse => tmch_proto::TMCHDocumentClass::OtherProofOfUse,
                DocumentClass::CopyOfCourtOrder => tmch_proto::TMCHDocumentClass::CopyOfCourtOrder,
                DocumentClass::Other => tmch_proto::TMCHDocumentClass::Other,
            },
            file_name: Some(from.file_name.to_string()),
            file_type: match from.file_type {
                FileType::Jpg => tmch_proto::TMCHFileType::Jpg,
                FileType::Pdf => tmch_proto::TMCHFileType::Pdf,
            },
            file_content: base64::encode(&from.contents),
        }
    }
}

impl From<&CaseDocument> for tmch_proto::TMCHCaseDocument {
    fn from(from: &CaseDocument) -> Self {
        tmch_proto::TMCHCaseDocument {
            document_class: match from.class {
                CaseDocumentClass::CourtDecision => {
                    tmch_proto::TMCHCaseDocumentClass::CourtCaseDocument
                }
                CaseDocumentClass::Other => tmch_proto::TMCHCaseDocumentClass::Other,
            },
            file_name: Some(from.file_name.to_string()),
            file_type: match from.file_type {
                FileType::Jpg => tmch_proto::TMCHFileType::Jpg,
                FileType::Pdf => tmch_proto::TMCHFileType::Pdf,
            },
            file_content: base64::encode(&from.contents),
        }
    }
}

impl From<&AddCase> for tmch_proto::TMCHCase {
    fn from(from: &AddCase) -> Self {
        tmch_proto::TMCHCase {
            id: from.id.to_string(),
            case_type: None,
            documents: from.documents.iter().map(Into::into).collect(),
            labels: from
                .labels
                .iter()
                .map(|l| tmch_proto::TMCHCaseLabel {
                    label: l.to_string(),
                })
                .collect(),
        }
    }
}

impl From<&CaseType> for tmch_proto::TMCHCaseType {
    fn from(from: &CaseType) -> Self {
        match from {
            CaseType::Court {
                decision_id,
                country_code,
                regions,
                court_name,
                case_language,
            } => tmch_proto::TMCHCaseType::Court(tmch_proto::TMCHCourt {
                reference: decision_id.to_string(),
                country_code: country_code.to_string(),
                regions: regions.iter().map(Into::into).collect(),
                court_name: court_name.to_string(),
                case_language: case_language.to_string(),
            }),
            CaseType::Udrp {
                case_language,
                case_id,
                provider,
            } => tmch_proto::TMCHCaseType::Udrp(tmch_proto::TMCHUdrp {
                case_number: case_id.to_string(),
                udrp_provider: provider.to_string(),
                case_language: case_language.to_string(),
            }),
        }
    }
}

pub fn handle_check(_client: &(), req: &CheckRequest) -> HandleReqReturn<CheckResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHCheck {
        id: vec![req.id.to_string()],
    };
    Ok(tmch_proto::TMCHCommandType::Check(command))
}

pub fn handle_check_response(response: tmch_proto::TMCHResponse) -> Response<CheckResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHCheck(msg) => {
                if let Some(mark_check) = msg.data.first() {
                    Response::Ok(CheckResponse {
                        avail: mark_check.id.available,
                        reason: mark_check.reason.as_ref().map(Into::into),
                    })
                } else {
                    Err(Error::ServerInternal)
                }
            }
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_create(_client: &(), req: &CreateRequest) -> HandleReqReturn<CreateResponse> {
    let command = tmch_proto::TMCHCreate {
        mark: Some((&req.mark).into()),
        period: match req.period.as_ref() {
            Some(r) => Some(r.try_into().map_err(Result::Err)?),
            None => None,
        },
        documents: req.documents.iter().map(Into::into).collect(),
        labels: req.labels.iter().map(Into::into).collect(),
        variations: if req.variations.is_empty() {
            vec![]
        } else {
            vec![tmch_proto::variation::Variation {
                labels: req
                    .variations
                    .iter()
                    .map(|l| tmch_proto::variation::Label {
                        id: None,
                        a_label: l.to_string(),
                        u_label: None,
                        variation_type: None,
                        active: None,
                    })
                    .collect(),
            }]
        },
    };
    Ok(tmch_proto::TMCHCommandType::Create(Box::new(command)))
}

pub fn handle_create_response(response: tmch_proto::TMCHResponse) -> Response<CreateResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHCreate(msg) => Response::Ok(CreateResponse {
                id: msg.id,
                created_date: msg.creation_date,
                balance: msg.balance.into(),
            }),
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_mark_info(_client: &(), req: &MarkInfoRequest) -> HandleReqReturn<MarkInfoResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHInfo {
        id: req.id.to_string(),
        id_type: tmch_proto::TMCHInfoType::Info,
    };
    Ok(tmch_proto::TMCHCommandType::Info(command))
}

pub fn handle_mark_smd_info(
    _client: &(),
    req: &MarkSMDInfoRequest,
) -> HandleReqReturn<MarkSMDInfoResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHInfo {
        id: req.id.to_string(),
        id_type: tmch_proto::TMCHInfoType::SingedMark,
    };
    Ok(tmch_proto::TMCHCommandType::Info(command))
}

pub fn handle_mark_encoded_smd_info(
    _client: &(),
    req: &MarkSMDInfoRequest,
) -> HandleReqReturn<MarkSMDInfoResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHInfo {
        id: req.id.to_string(),
        id_type: tmch_proto::TMCHInfoType::EncodedSignedMark,
    };
    Ok(tmch_proto::TMCHCommandType::Info(command))
}

pub fn handle_mark_file_info(
    _client: &(),
    req: &MarkSMDInfoRequest,
) -> HandleReqReturn<MarkSMDInfoResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHInfo {
        id: req.id.to_string(),
        id_type: tmch_proto::TMCHInfoType::File,
    };
    Ok(tmch_proto::TMCHCommandType::Info(command))
}

impl From<tmch_proto::TMCHStatus<tmch_proto::TMCHStatusType>> for Status<MarkStatus> {
    fn from(from: tmch_proto::TMCHStatus<tmch_proto::TMCHStatusType>) -> Self {
        Status {
            status_type: match from.status {
                tmch_proto::TMCHStatusType::New => MarkStatus::New,
                tmch_proto::TMCHStatusType::Verified => MarkStatus::Verified,
                tmch_proto::TMCHStatusType::Incorrect => MarkStatus::Incorrect,
                tmch_proto::TMCHStatusType::Corrected => MarkStatus::Corrected,
                tmch_proto::TMCHStatusType::Invalid => MarkStatus::Invalid,
                tmch_proto::TMCHStatusType::Expired => MarkStatus::Expired,
                tmch_proto::TMCHStatusType::Deactivated => MarkStatus::Deactivated,
            },
            message: from.message,
        }
    }
}

impl From<tmch_proto::TMCHStatus<tmch_proto::TMCHPOUStatusType>> for Status<MarkPOUStatus> {
    fn from(from: tmch_proto::TMCHStatus<tmch_proto::TMCHPOUStatusType>) -> Self {
        Status {
            status_type: match from.status {
                tmch_proto::TMCHPOUStatusType::NotSet => MarkPOUStatus::NotSet,
                tmch_proto::TMCHPOUStatusType::NA => MarkPOUStatus::NA,
                tmch_proto::TMCHPOUStatusType::New => MarkPOUStatus::New,
                tmch_proto::TMCHPOUStatusType::Incorrect => MarkPOUStatus::Incorrect,
                tmch_proto::TMCHPOUStatusType::Corrected => MarkPOUStatus::Corrected,
                tmch_proto::TMCHPOUStatusType::Valid => MarkPOUStatus::Valid,
                tmch_proto::TMCHPOUStatusType::Invalid => MarkPOUStatus::Invalid,
                tmch_proto::TMCHPOUStatusType::Expired => MarkPOUStatus::Expired,
            },
            message: from.message,
        }
    }
}

impl From<tmch_proto::trex::TLDStatus> for TrexStatus {
    fn from(from: tmch_proto::trex::TLDStatus) -> Self {
        match from {
            tmch_proto::trex::TLDStatus::NotProtectedRegistered => {
                TrexStatus::NotProtectedRegistered
            }
            tmch_proto::trex::TLDStatus::NotProtectedExempt => TrexStatus::NotProtectedExempt,
            tmch_proto::trex::TLDStatus::NotProtectedOther => TrexStatus::NotProtectedOther,
            tmch_proto::trex::TLDStatus::NotProtectedOverride => TrexStatus::NotProtectedOverride,
            tmch_proto::trex::TLDStatus::Eligible => TrexStatus::Eligible,
            tmch_proto::trex::TLDStatus::Protected => TrexStatus::Protected,
            tmch_proto::trex::TLDStatus::Unavailable => TrexStatus::Unavailable,
            tmch_proto::trex::TLDStatus::NoInfo => TrexStatus::NoInfo,
        }
    }
}

impl From<tmch_proto::TMCHInfoLabel> for MarkLabel {
    fn from(from: tmch_proto::TMCHInfoLabel) -> Self {
        MarkLabel {
            a_label: from.label,
            u_label: from.ulabel,
            smd_inclusion: from.smd_inclusion.map(|n| n.enable).unwrap_or(false),
            claim_notify: from.claims_notify.map(|n| n.enable).unwrap_or(false),
            trex: from.trex.map(Into::into),
        }
    }
}

impl From<tmch_proto::variation::Label> for MarkVariation {
    fn from(from: tmch_proto::variation::Label) -> Self {
        MarkVariation {
            a_label: from.a_label.clone(),
            u_label: from.u_label.unwrap_or(from.a_label),
            variation_type: from.variation_type.unwrap_or_default(),
            active: from.active.map(|a| a.enable).unwrap_or(true),
        }
    }
}

impl From<tmch_proto::TMCHBalance> for BalanceData {
    fn from(from: tmch_proto::TMCHBalance) -> Self {
        BalanceData {
            value: from.amount.value,
            currency: from.amount.currency,
            status_points: from.status_points,
        }
    }
}

impl TryFrom<&Period> for tmch_proto::TMCHPeriod {
    type Error = Error;

    fn try_from(from: &Period) -> Result<Self, Self::Error> {
        Ok(tmch_proto::TMCHPeriod {
            value: std::cmp::min(99, std::cmp::max(from.value, 1)),
            unit: match from.unit {
                PeriodUnit::Years => tmch_proto::TMCHPeriodUnit::Years,
                PeriodUnit::Months => {
                    return Err(Error::Err(
                        "month based periods are not valid for TMCH".to_string(),
                    ))
                }
            },
        })
    }
}

pub fn handle_mark_info_response(response: tmch_proto::TMCHResponse) -> Response<MarkInfoResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHInfo(msg) => match (msg.pou_status, msg.mark) {
                (Some(pou_status), Some(_mark)) => Response::Ok(MarkInfoResponse {
                    id: msg.id,
                    status: msg.status.into(),
                    pou_status: pou_status.into(),
                    labels: msg.labels.into_iter().map(Into::into).collect(),
                    variations: msg
                        .variations
                        .into_iter()
                        .flat_map(|v| v.labels)
                        .map(Into::into)
                        .collect(),
                    creation_date: msg.creation_date,
                    update_date: msg.update_date,
                    expiry_date: msg.expiry_date,
                    pou_expiry_date: msg.pou_expiry_date,
                    correct_before: msg.correct_before,
                }),
                _ => Err(Error::ServerInternal),
            },
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

#[derive(Debug, Serialize)]
struct SMDInfo {
    #[serde(rename = "{urn:ietf:params:xml:ns:signedMark-1.0}signedMark")]
    pub signed_mark: String,
}

pub fn handle_mark_smd_info_response(
    response: tmch_proto::TMCHResponse,
) -> Response<MarkSMDInfoResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHInfo(msg) => match (msg.signed_mark, msg.smd_id) {
                (Some(smd), Some(smd_id)) => {
                    let smd = SMDInfo { signed_mark: smd };

                    Response::Ok(MarkSMDInfoResponse {
                        id: msg.id,
                        status: msg.status.into(),
                        smd_id,
                        smd: xml_serde::to_string(&smd).unwrap(),
                    })
                }
                _ => Err(Error::ServerInternal),
            },
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_mark_encoded_smd_info_response(
    response: tmch_proto::TMCHResponse,
) -> Response<MarkSMDInfoResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHInfo(msg) => {
                match (msg.encoded_signed_mark, msg.smd_id) {
                    (Some(smd), Some(smd_id)) => Response::Ok(MarkSMDInfoResponse {
                        id: msg.id,
                        status: msg.status.into(),
                        smd_id,
                        smd,
                    }),
                    _ => Err(Error::ServerInternal),
                }
            }
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_mark_file_info_response(
    response: tmch_proto::TMCHResponse,
) -> Response<MarkSMDInfoResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHInfo(msg) => match (msg.enc_file, msg.smd_id) {
                (Some(smd), Some(smd_id)) => Response::Ok(MarkSMDInfoResponse {
                    id: msg.id,
                    status: msg.status.into(),
                    smd_id,
                    smd,
                }),
                _ => Err(Error::ServerInternal),
            },
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_update(_client: &(), req: &UpdateRequest) -> HandleReqReturn<UpdateResponse> {
    let mut add_documents: Vec<tmch_proto::TMCHDocument> = vec![];
    let mut add_labels: Vec<tmch_proto::TMCHLabel> = vec![];
    let mut add_variations: Vec<String> = vec![];
    let mut add_cases: Vec<tmch_proto::TMCHCase> = vec![];
    let mut rem_labels: Vec<tmch_proto::TMCHLabel> = vec![];
    let mut rem_variations: Vec<String> = vec![];
    let mut rem_cases: Vec<tmch_proto::TMCHCase> = vec![];
    let mut chg_cases: Vec<tmch_proto::TMCHCaseType> = vec![];

    for add in &req.add {
        match add {
            UpdateAdd::Document(d) => {
                add_documents.push(d.into());
            }
            UpdateAdd::Label(d) => {
                add_labels.push(d.into());
            }
            UpdateAdd::Variation(d) => {
                add_variations.push(d.to_string());
            }
            UpdateAdd::Case(d) => {
                check_case_id(&d.id)?;
                add_cases.push(d.into());
            }
        }
    }

    for remove in &req.remove {
        match remove {
            UpdateRemove::Label(d) => {
                rem_labels.push(tmch_proto::TMCHLabel {
                    label: d.to_string(),
                    smd_inclusion: None,
                    claims_notify: None,
                    trex_activate: None,
                    trex_renew: None,
                });
            }
            UpdateRemove::Variation(d) => {
                rem_variations.push(d.to_string());
            }
        }
    }

    for case in &req.update_cases {
        check_case_id(&case.id)?;
        let mut add_case_documents: Vec<tmch_proto::TMCHCaseDocument> = vec![];
        let mut add_case_labels: Vec<tmch_proto::TMCHCaseLabel> = vec![];
        let mut rem_case_labels: Vec<tmch_proto::TMCHCaseLabel> = vec![];
        for case_add in &case.add {
            match case_add {
                CaseAdd::Document(d) => {
                    add_case_documents.push(d.into());
                }
                CaseAdd::Label(l) => {
                    add_case_labels.push(tmch_proto::TMCHCaseLabel {
                        label: l.to_string(),
                    });
                }
            }
        }
        for case_rem in &case.remove {
            match case_rem {
                CaseRemove::Label(l) => {
                    rem_case_labels.push(tmch_proto::TMCHCaseLabel {
                        label: l.to_string(),
                    });
                }
            }
        }

        if !(add_case_labels.is_empty() && add_case_documents.is_empty()) {
            add_cases.push(tmch_proto::TMCHCase {
                id: case.id.clone(),
                case_type: None,
                documents: add_case_documents,
                labels: add_case_labels,
            })
        }

        if !rem_case_labels.is_empty() {
            rem_cases.push(tmch_proto::TMCHCase {
                id: case.id.clone(),
                case_type: None,
                documents: vec![],
                labels: rem_case_labels,
            })
        }

        if let Some(case) = &case.new_case {
            chg_cases.push(case.into())
        }
    }

    let command = tmch_proto::TMCHUpdate {
        id: req.id.to_string(),
        case: None,
        add: if add_documents.is_empty()
            && add_labels.is_empty()
            && add_variations.is_empty()
            && add_cases.is_empty()
        {
            None
        } else {
            Some(tmch_proto::TMCHAdd {
                documents: add_documents,
                labels: add_labels,
                variations: if add_variations.is_empty() {
                    vec![]
                } else {
                    vec![tmch_proto::variation::Variation {
                        labels: add_variations
                            .into_iter()
                            .map(|l| tmch_proto::variation::Label {
                                id: None,
                                a_label: l,
                                u_label: None,
                                active: None,
                                variation_type: None,
                            })
                            .collect(),
                    }]
                },
                cases: add_cases,
            })
        },
        remove: if rem_labels.is_empty() && rem_variations.is_empty() && rem_cases.is_empty() {
            None
        } else {
            Some(tmch_proto::TMCHRemove {
                labels: rem_labels,
                variations: if rem_variations.is_empty() {
                    vec![]
                } else {
                    vec![tmch_proto::variation::Variation {
                        labels: rem_variations
                            .into_iter()
                            .map(|l| tmch_proto::variation::Label {
                                id: None,
                                a_label: l,
                                u_label: None,
                                active: None,
                                variation_type: None,
                            })
                            .collect(),
                    }]
                },
                cases: rem_cases,
            })
        },
        change: if req.new_mark.is_none() && req.update_labels.is_empty() {
            None
        } else {
            Some(tmch_proto::TMCHChange {
                mark: req.new_mark.as_ref().map(Into::into),
                labels: req.update_labels.iter().map(Into::into).collect(),
                case: None,
            })
        },
    };
    Ok(tmch_proto::TMCHCommandType::Update(Box::new(command)))
}

pub fn handle_update_response(response: tmch_proto::TMCHResponse) -> Response<UpdateResponse> {
    match response.data {
        Some(_) => Err(Error::ServerInternal),
        None => Response::Ok(UpdateResponse {}),
    }
}

pub fn handle_renew(_client: &(), req: &RenewRequest) -> HandleReqReturn<RenewResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHRenew {
        id: req.id.to_string(),
        current_expiry_date: req.cur_expiry_date.date(),
        period: match req.add_period.as_ref() {
            Some(r) => Some(r.try_into().map_err(Result::Err)?),
            None => None,
        },
    };
    Ok(tmch_proto::TMCHCommandType::Renew(command))
}

pub fn handle_renew_response(response: tmch_proto::TMCHResponse) -> Response<RenewResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHRenew(msg) => Response::Ok(RenewResponse {
                id: msg.id,
                new_expiry_date: msg.expiry_date,
                balance: msg.balance.into(),
            }),
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_transfer_initiate(
    _client: &(),
    req: &TransferInitiateRequest,
) -> HandleReqReturn<TransferInitiateResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHTransfer {
        id: req.id.to_string(),
        auth_code: None,
        operation: tmch_proto::TMCHTransferOperation::Initiate,
    };
    Ok(tmch_proto::TMCHCommandType::Transfer(command))
}

pub fn handle_transfer_initiate_response(
    response: tmch_proto::TMCHResponse,
) -> Response<TransferInitiateResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHInfo(msg) => match msg.auth_info {
                Some(auth_info) => Response::Ok(TransferInitiateResponse {
                    id: msg.id,
                    auth_info,
                }),
                None => Err(Error::ServerInternal),
            },
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}

pub fn handle_transfer(_client: &(), req: &TransferRequest) -> HandleReqReturn<TransferResponse> {
    check_mark_id(&req.id)?;
    let command = tmch_proto::TMCHTransfer {
        id: req.id.to_string(),
        auth_code: Some(req.auth_info.to_string()),
        operation: tmch_proto::TMCHTransferOperation::Execute,
    };
    Ok(tmch_proto::TMCHCommandType::Transfer(command))
}

pub fn handle_transfer_response(response: tmch_proto::TMCHResponse) -> Response<TransferResponse> {
    match response.data {
        Some(value) => match value.value {
            tmch_proto::TMCHResultDataValue::TMCHTransfer(msg) => Response::Ok(TransferResponse {
                id: msg.id,
                transfer_date: msg.transfer_date,
                balance: msg.balance.into(),
            }),
            _ => Err(Error::ServerInternal),
        },
        None => Err(Error::ServerInternal),
    }
}