This repository has been archived by the owner on Dec 3, 2020. It is now read-only.
/
any_schedule.go
90 lines (79 loc) · 2.18 KB
/
any_schedule.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
package recurrence
import (
"encoding/json"
"fmt"
"time"
)
// AnySchedule acts as a wrapper around...any schedule. Why does this exists?
// Since the tree of Schedules is an arbitrary relationship of interfaces, we
// need a struct to *easily* marshal/unmarshal json of the entire schedule
// hierarchy.
type AnySchedule struct {
Schedule Schedule
}
// IsOccurring implements the Schedule interface.
func (a AnySchedule) IsOccurring(t time.Time) bool {
return a.Schedule.IsOccurring(t)
}
// Occurrences implements the Schedule interface.
func (a AnySchedule) Occurrences(t TimeRange) chan time.Time {
return a.Schedule.Occurrences(t)
}
// MarshalJSON implements the json.Marshaler interface.
func (a AnySchedule) MarshalJSON() ([]byte, error) {
return json.Marshal(a.Schedule)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (a *AnySchedule) UnmarshalJSON(b []byte) error {
schedule, err := ScheduleUnmarshalJSON(b)
if err != nil {
return err
}
a.Schedule = schedule
return nil
}
// ScheduleUnmarshalJSON unmarshals bytes representing any arbitrary relationship of schedules.
func ScheduleUnmarshalJSON(b []byte) (schedule Schedule, err error) {
var mixed interface{}
json.Unmarshal(b, &mixed)
for key, value := range mixed.(map[string]interface{}) {
rawValue, _ := json.Marshal(value)
switch key {
case "date":
var date Date
err = json.Unmarshal(rawValue, &date)
schedule = date
case "day":
var day Day
err = json.Unmarshal(rawValue, &day)
schedule = day
case "intersection":
var intersection Intersection
err = json.Unmarshal(rawValue, &intersection)
schedule = intersection
case "month":
var month Month
err = json.Unmarshal(rawValue, &month)
schedule = month
case "union":
var union Union
err = json.Unmarshal(rawValue, &union)
schedule = union
case "week":
var week Week
err = json.Unmarshal(rawValue, &week)
schedule = week
case "weekday":
var weekday Weekday
err = json.Unmarshal(rawValue, &weekday)
schedule = weekday
case "year":
var year Year
err = json.Unmarshal(rawValue, &year)
schedule = year
default:
err = fmt.Errorf("%s is not a recognized schedule", key)
}
}
return
}