package command import ( "fmt" "strings" "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 title string flags map[string]Flag } func NewAddCmd(localRepo storage.LocalID, eventRepo storage.Event, syncRepo storage.Sync) Command { return &AddCmd{ localIDRepo: localRepo, eventRepo: eventRepo, syncRepo: syncRepo, flags: map[string]Flag{ FlagOn: &FlagDate{}, FlagAt: &FlagTime{}, FlagFor: &FlagDuration{}, }, } } func (add *AddCmd) Parse(as *ArgSet) error { if len(as.Main) == 0 || as.Main[0] != "add " { return ErrWrongCommand } add.title = strings.Join(as.Main[1:], " ") for k := range add.flags { if err := add.flags[k].Set(as.Flags[k]); err != nil { return fmt.Errorf("could not set %s: %v", k, err) } } if add.title == "" { return fmt.Errorf("%w: title is required", ErrInvalidArg) } if !add.flags[FlagOn].IsSet() { return fmt.Errorf("%w: date is required", ErrInvalidArg) } if !add.flags[FlagAt].IsSet() && add.flags[FlagFor].IsSet() { return fmt.Errorf("%w: can not have duration without start time", ErrInvalidArg) } if !add.flags[FlagAt].IsSet() && !add.flags[FlagFor].IsSet() { if err := add.flags[FlagFor].Set("24h"); err != nil { return fmt.Errorf("could not set duration to 24 hours") } } return nil } func (add *AddCmd) Do() 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 }