-
Notifications
You must be signed in to change notification settings - Fork 0
/
calendar.go
223 lines (206 loc) · 6.65 KB
/
calendar.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
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
// Copyright ©2017-2022 by Richard A. Wilkes. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, version 2.0.
// Package calendar provides a customizable calendar for roleplaying games.
package calendar
import (
"fmt"
"io"
"regexp"
"strconv"
"strings"
"github.com/richardwilkes/toolbox/errs"
"github.com/richardwilkes/toolbox/txt"
)
var (
// Default is the default calendar that will be used by Date.UnmarshalText() if the date was not initialized.
Default = Gregorian()
// "9/22/2017" or "9/22/2017 AD"
regexMMDDYYY = regexp.MustCompile("([[:digit:]]+)/([[:digit:]]+)/(-?[[:digit:]]+) *([[:alpha:]]+)?")
// "September 22, 2017 AD", "September 22, 2017", "Sep 22, 2017 AD", or "Sep 22, 2017"
regexMonthDDYYYY = regexp.MustCompile("([[:alpha:]]+) *([[:digit:]]+), *(-?[[:digit:]]+) *([[:alpha:]]+)?")
)
// Calendar holds the data for the calendar.
type Calendar struct {
DayZeroWeekDay int `json:"day_zero_weekday" yaml:"day_zero_weekday"`
WeekDays []string `json:"weekdays"`
Months []Month `json:"months"`
Seasons []Season `json:"seasons"`
Era string `json:"era,omitempty" yaml:",omitempty"`
PreviousEra string `json:"previous_era,omitempty" yaml:"previous_era,omitempty"`
LeapYear *LeapYear `json:"leapyear,omitempty" yaml:",omitempty"`
}
// Valid returns nil if the calendar data is usable.
func (cal *Calendar) Valid() error {
if len(cal.WeekDays) == 0 {
return errs.New("Calendar must have at least one week day")
}
if len(cal.Months) == 0 {
return errs.New("Calendar must have at least one month")
}
if len(cal.Seasons) == 0 {
return errs.New("Calendar must have at least one season")
}
if cal.DayZeroWeekDay < 0 || cal.DayZeroWeekDay >= len(cal.WeekDays) {
return errs.New("Calendar's first week day of the first year must be a valid week day")
}
for _, weekday := range cal.WeekDays {
if weekday == "" {
return errs.New("Calendar week day names must not be empty")
}
}
for _, month := range cal.Months {
if err := month.Valid(); err != nil {
return err
}
}
for i := range cal.Seasons {
if err := cal.Seasons[i].Valid(cal); err != nil {
return err
}
}
if cal.LeapYear != nil {
if err := cal.LeapYear.Valid(cal); err != nil {
return err
}
}
return nil
}
// MustNewDate creates a new date from the specified month, day and year. Panics if the values are invalid.
func (cal *Calendar) MustNewDate(month, day, year int) Date {
date, err := cal.NewDate(month, day, year)
if err != nil {
panic(err) // @allow
}
return date
}
// NewDate creates a new date from the specified month, day and year.
func (cal *Calendar) NewDate(month, day, year int) (Date, error) {
if year == 0 {
return Date{cal: cal}, errs.New("year 0 is invalid")
}
if month < 1 || month > len(cal.Months) {
return Date{cal: cal}, errs.Newf("month %d is invalid", month)
}
days := cal.Months[month-1].Days
if cal.IsLeapMonth(month) && cal.IsLeapYear(year) {
days++
}
if day < 1 || day > days {
return Date{cal: cal}, errs.Newf("day %d is invalid", day)
}
days = cal.yearToDays(year) + day - 1
for i := 1; i < month; i++ {
days += cal.Months[i-1].Days
}
if cal.IsLeapYear(year) && cal.LeapYear.Month < month {
days++
}
return Date{Days: days, cal: cal}, nil
}
// NewDateByDays creates a new date from a number of days, with 0 representing the date 1/1/1.
func (cal *Calendar) NewDateByDays(days int) Date {
return Date{Days: days, cal: cal}
}
func (cal *Calendar) yearToDays(year int) int {
var days int
if year > 1 {
days = (year - 1) * cal.MinDaysPerYear()
} else if year < 0 {
days = year * cal.MinDaysPerYear()
}
if cal.LeapYear != nil {
leaps := cal.LeapYear.Since(year)
if year > 1 {
days += leaps
} else {
days -= leaps
if cal.LeapYear.Is(year) {
days--
}
}
}
return days
}
// ParseDate creates a new date from the specified text.
func (cal *Calendar) ParseDate(in string) (Date, error) {
if parts := regexMMDDYYY.FindStringSubmatch(in); parts != nil {
month, err := strconv.Atoi(parts[1])
if err != nil {
return Date{cal: cal}, errs.NewWithCausef(err, "invalid month text '%s'", parts[1])
}
return cal.parseDate(month, parts[2], parts[3], parts[4])
}
if parts := regexMonthDDYYYY.FindStringSubmatch(in); parts != nil {
for i, month := range cal.Months {
if strings.EqualFold(parts[1], month.Name) || strings.EqualFold(parts[1], txt.FirstN(month.Name, 3)) {
return cal.parseDate(i+1, parts[2], parts[3], parts[4])
}
}
return Date{cal: cal}, errs.Newf("invalid month text '%s'", parts[1])
}
return Date{cal: cal}, errs.Newf("invalid date text '%s'", in)
}
func (cal *Calendar) parseDate(month int, dayText, yearText, eraText string) (Date, error) {
year, err := strconv.Atoi(yearText)
if err != nil {
return Date{cal: cal}, errs.NewWithCausef(err, "invalid year text '%s'", yearText)
}
day, err := strconv.Atoi(dayText)
if err != nil {
return Date{cal: cal}, errs.NewWithCausef(err, "invalid day text '%s'", dayText)
}
if cal.PreviousEra != "" && cal.PreviousEra != cal.Era && strings.EqualFold(cal.PreviousEra, eraText) {
year = -year
}
return cal.NewDate(month, day, year)
}
// MinDaysPerYear returns the minimum number of days in a year.
func (cal *Calendar) MinDaysPerYear() int {
days := 0
for _, month := range cal.Months {
days += month.Days
}
return days
}
// Days returns the number of days contained in a specific year.
func (cal *Calendar) Days(year int) int {
days := cal.MinDaysPerYear()
if cal.IsLeapYear(year) {
days++
}
return days
}
// IsLeapYear returns true if the year is a leap year.
func (cal *Calendar) IsLeapYear(year int) bool {
return cal.LeapYear != nil && cal.LeapYear.Is(year)
}
// IsLeapMonth returns true if the month is the leap month.
func (cal *Calendar) IsLeapMonth(month int) bool {
return cal.LeapYear != nil && cal.LeapYear.Month == month
}
// Text writes a text representation of the year.
func (cal *Calendar) Text(year int, w io.Writer) {
date := cal.MustNewDate(1, 1, year)
date.WriteFormat(w, "Year %Y\n")
maximum := len(cal.Months)
for i := 1; i <= maximum; i++ {
fmt.Fprintln(w)
cal.MustNewDate(i, 1, year).TextCalendarMonth(w)
}
fmt.Fprintln(w)
fmt.Fprintln(w, "Seasons:")
for i := range cal.Seasons {
fmt.Fprintf(w, " %v\n", &cal.Seasons[i])
}
fmt.Fprintln(w)
fmt.Fprintln(w, "Week Days:")
for i, weekday := range cal.WeekDays {
fmt.Fprintf(w, " %d: (%s) %s\n", i+1, weekday[:1], weekday)
}
}