-
Notifications
You must be signed in to change notification settings - Fork 2
/
card.go
129 lines (108 loc) · 2.6 KB
/
card.go
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
package types
import (
"encoding/json"
"fmt"
)
type Card struct {
CardNumber uint32 `json:"card-number"`
From Date `json:"start-date"`
To Date `json:"end-date"`
Doors map[uint8]uint8 `json:"doors"`
PIN PIN `json:"PIN,omitempty"`
}
func (c Card) String() string {
f := func(p uint8) string {
switch {
case p == 0:
return "N"
case p == 1:
return "Y"
case p >= 2 && p <= 254:
return fmt.Sprintf("%v", p)
default:
return "N"
}
}
var from string
if c.From.IsZero() {
from = "-"
} else {
from = fmt.Sprintf("%v", c.From)
}
var to string
if c.To.IsZero() {
to = "-"
} else {
to = fmt.Sprintf("%v", c.To)
}
if c.PIN == 0 || c.PIN > 999999 {
return fmt.Sprintf("%-8v %-10v %-10v %v %v %v %v", c.CardNumber, from, to, f(c.Doors[1]), f(c.Doors[2]), f(c.Doors[3]), f(c.Doors[4]))
} else {
return fmt.Sprintf("%-8v %-10v %-10v %v %v %v %v %v", c.CardNumber, from, to, f(c.Doors[1]), f(c.Doors[2]), f(c.Doors[3]), f(c.Doors[4]), c.PIN)
}
}
func (c Card) MarshalJSON() ([]byte, error) {
card := struct {
CardNumber uint32 `json:"card-number"`
From Date `json:"start-date"`
To Date `json:"end-date"`
Doors map[uint8]uint8 `json:"doors"`
PIN PIN `json:"PIN,omitempty"`
}{
CardNumber: c.CardNumber,
From: c.From,
To: c.To,
Doors: c.Doors,
PIN: c.PIN,
}
if card.PIN > 999999 {
card.PIN = 0
}
return json.Marshal(card)
}
func (c *Card) UnmarshalJSON(bytes []byte) error {
card := struct {
CardNumber uint32 `json:"card-number"`
From string `json:"start-date"`
To string `json:"end-date"`
Doors map[uint8]int `json:"doors"`
PIN PIN `json:"PIN"`
}{
Doors: map[uint8]int{1: 0, 2: 0, 3: 0, 4: 0},
}
if err := json.Unmarshal(bytes, &card); err != nil {
return err
}
from, err := DateFromString(card.From)
if err != nil {
return fmt.Errorf("invalid start-date '%s'", card.From)
}
to, err := DateFromString(card.To)
if err != nil {
return fmt.Errorf("invalid end-date '%s'", card.To)
}
c.CardNumber = card.CardNumber
c.From = from
c.To = to
c.Doors = map[uint8]uint8{}
c.PIN = card.PIN
for _, i := range []uint8{1, 2, 3, 4} {
c.Doors[i] = uint8(card.Doors[i])
}
return nil
}
func (c *Card) Clone() Card {
card := Card{
CardNumber: c.CardNumber,
From: c.From,
To: c.To,
Doors: map[uint8]uint8{
1: c.Doors[1],
2: c.Doors[2],
3: c.Doors[3],
4: c.Doors[4],
},
PIN: c.PIN,
}
return card
}