planner/plan/command/add.go

109 lines
2.4 KiB
Go

package command
import (
"fmt"
"time"
"github.com/google/uuid"
"go-mod.ewintr.nl/planner/item"
"go-mod.ewintr.nl/planner/plan/storage"
)
const (
FlagOn = "on"
FlagAt = "at"
FlagFor = "for"
)
type AddCmd struct {
localIDRepo storage.LocalID
eventRepo storage.Event
syncRepo storage.Sync
}
func NewAddCmd(localRepo storage.LocalID, eventRepo storage.Event, syncRepo storage.Sync) Command {
return &AddCmd{
localIDRepo: localRepo,
eventRepo: eventRepo,
syncRepo: syncRepo,
}
}
func (add *AddCmd) Parse(args []string) (*ArgSet, error) {
if len(args) == 0 || args[0] != "add" {
return nil, ErrWrongCommand
}
as, err := ParseArgs(args[1:])
if err != nil {
return nil, err
}
if as.Main == "" {
return nil, fmt.Errorf("%w: title is required", ErrInvalidArg)
}
if !as.HasFlag(FlagOn) {
return nil, fmt.Errorf("%w: date is required", ErrInvalidArg)
}
if !as.HasFlag(FlagAt) && !as.HasFlag(FlagFor) {
return nil, fmt.Errorf("%w: can not have duration without start time", ErrInvalidArg)
}
if !as.HasFlag(FlagAt) && !as.HasFlag(FlagFor) {
as.SetFlag(FlagFor, "24h")
}
if err := add.Do(as); err != nil {
return nil, err
}
return as, nil
}
func (add *AddCmd) Do(as *ArgSet) error {
startFormat := "2006-01-02"
startStr := as.Flag(FlagOn)
if as.HasFlag(FlagAt) {
startFormat = fmt.Sprintf("%s 15:04", startFormat)
startStr = fmt.Sprintf("%s %s", startStr, as.Flag(FlagAt))
}
start, err := time.Parse(startFormat, startStr)
if err != nil {
return fmt.Errorf("%w: could not parse start time and date: %v", ErrInvalidArg, err)
}
e := item.Event{
ID: uuid.New().String(),
EventBody: item.EventBody{
Title: as.Main,
Start: start,
},
}
if as.HasFlag(FlagFor) {
fr, err := time.ParseDuration(as.Flag(FlagFor))
if err != nil {
return fmt.Errorf("%w: could not parse duration: %s", ErrInvalidArg, err)
}
e.Duration = fr
}
if err := add.eventRepo.Store(e); err != nil {
return fmt.Errorf("could not store event: %v", err)
}
localID, err := add.localIDRepo.Next()
if err != nil {
return fmt.Errorf("could not create next local id: %v", err)
}
if err := add.localIDRepo.Store(e.ID, localID); err != nil {
return fmt.Errorf("could not store local id: %v", err)
}
it, err := e.Item()
if err != nil {
return fmt.Errorf("could not convert event to sync item: %v", err)
}
if err := add.syncRepo.Store(it); err != nil {
return fmt.Errorf("could not store sync item: %v", err)
}
return nil
}