planner/item/event.go

117 lines
2.1 KiB
Go
Raw Normal View History

2024-09-20 07:09:30 +02:00
package item
import (
"encoding/json"
"fmt"
"time"
2024-12-19 12:06:03 +01:00
"github.com/google/go-cmp/cmp"
2024-09-20 07:09:30 +02:00
)
type EventBody struct {
2024-09-26 07:21:48 +02:00
Title string `json:"title"`
2024-12-19 12:06:03 +01:00
Time Time `json:"time"`
2024-09-26 07:21:48 +02:00
Duration time.Duration `json:"duration"`
2024-09-20 07:09:30 +02:00
}
func (e EventBody) MarshalJSON() ([]byte, error) {
type Alias EventBody
return json.Marshal(&struct {
2024-09-26 07:21:48 +02:00
Duration string `json:"duration"`
2024-09-20 07:09:30 +02:00
*Alias
}{
2024-09-26 07:21:48 +02:00
Duration: e.Duration.String(),
Alias: (*Alias)(&e),
2024-09-20 07:09:30 +02:00
})
}
2024-09-26 07:21:48 +02:00
func (e *EventBody) UnmarshalJSON(data []byte) error {
type Alias EventBody
aux := &struct {
Duration string `json:"duration"`
*Alias
}{
Alias: (*Alias)(e),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
var err error
if e.Duration, err = time.ParseDuration(aux.Duration); err != nil {
return err
}
return nil
}
2024-09-20 07:09:30 +02:00
type Event struct {
2024-12-19 12:06:03 +01:00
ID string `json:"id"`
Date Date `json:"date"`
Recurrer Recurrer `json:"recurrer"`
RecurNext Date `json:"recurNext"`
2024-09-20 07:09:30 +02:00
EventBody
}
func NewEvent(i Item) (Event, error) {
if i.Kind != KindEvent {
return Event{}, fmt.Errorf("item is not an event")
}
var e Event
if err := json.Unmarshal([]byte(i.Body), &e); err != nil {
return Event{}, fmt.Errorf("could not unmarshal item body: %v", err)
}
e.ID = i.ID
2024-12-19 12:06:03 +01:00
e.Date = i.Date
2024-12-01 10:22:47 +01:00
e.Recurrer = i.Recurrer
e.RecurNext = i.RecurNext
2024-09-20 07:09:30 +02:00
return e, nil
}
func (e Event) Item() (Item, error) {
2024-12-19 12:06:03 +01:00
body, err := json.Marshal(e.EventBody)
2024-09-20 07:09:30 +02:00
if err != nil {
2024-12-19 12:06:03 +01:00
return Item{}, fmt.Errorf("could not marshal event body to json")
2024-09-20 07:09:30 +02:00
}
return Item{
2024-12-01 10:22:47 +01:00
ID: e.ID,
Kind: KindEvent,
2024-12-19 12:06:03 +01:00
Date: e.Date,
2024-12-01 10:22:47 +01:00
Recurrer: e.Recurrer,
RecurNext: e.RecurNext,
Body: string(body),
2024-09-20 07:09:30 +02:00
}, nil
}
2024-10-29 07:22:04 +01:00
func (e Event) Valid() bool {
if e.Title == "" {
return false
}
2024-12-19 12:06:03 +01:00
if e.Date.IsZero() {
2024-10-29 07:22:04 +01:00
return false
}
if e.Duration.Seconds() < 1 {
return false
}
return true
}
2024-12-19 12:06:03 +01:00
func EventDiff(a, b Event) string {
aJSON, _ := json.Marshal(a)
bJSON, _ := json.Marshal(b)
return cmp.Diff(string(aJSON), string(bJSON))
}
func EventDiffs(a, b []Event) string {
aJSON, _ := json.Marshal(a)
bJSON, _ := json.Marshal(b)
return cmp.Diff(string(aJSON), string(bJSON))
}