planner/plan/command/add.go

104 lines
2.3 KiB
Go

package command
import (
"fmt"
"time"
"github.com/google/uuid"
"go-mod.ewintr.nl/planner/item"
"go-mod.ewintr.nl/planner/plan/storage"
)
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) Do(args []string) (bool, error) {
if len(args) == 0 || args[0] != "add" {
return false, nil
}
title, flags, err := ParseArgs(args[1:])
if err != nil {
return false, err
}
if nameStr == "" {
return fmt.Errorf("%w: name is required", ErrInvalidArg)
}
if onStr == "" {
return fmt.Errorf("%w: date is required", ErrInvalidArg)
}
if atStr == "" && frStr != "" {
return fmt.Errorf("%w: can not have duration without start time", ErrInvalidArg)
}
if atStr == "" && frStr == "" {
frStr = "24h"
}
if err := add.Action(title, flags); err != nil {
return false, err
}
return true, nil
}
func (add *AddCmd) Action(nameStr, onStr, atStr, frStr string) error {
startFormat := "2006-01-02"
startStr := onStr
if atStr != "" {
startFormat = fmt.Sprintf("%s 15:04", startFormat)
startStr = fmt.Sprintf("%s %s", startStr, atStr)
}
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: nameStr,
Start: start,
},
}
if frStr != "" {
fr, err := time.ParseDuration(frStr)
if err != nil {
return fmt.Errorf("%w: could not parse duration: %s", ErrInvalidArg, err)
}
e.Duration = fr
}
if err := eventRepo.Store(e); err != nil {
return fmt.Errorf("could not store event: %v", err)
}
localID, err := localIDRepo.Next()
if err != nil {
return fmt.Errorf("could not create next local id: %v", err)
}
if err := 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 := syncRepo.Store(it); err != nil {
return fmt.Errorf("could not store sync item: %v", err)
}
return nil
}