planner/plan/command/delete.go

77 lines
1.6 KiB
Go
Raw Normal View History

2024-10-07 09:34:17 +02:00
package command
import (
"fmt"
2024-10-29 07:22:04 +01:00
"strconv"
2024-10-07 09:34:17 +02:00
"go-mod.ewintr.nl/planner/plan/storage"
)
2024-10-29 07:22:04 +01:00
type Delete struct {
localIDRepo storage.LocalID
2024-12-24 08:00:23 +01:00
taskRepo storage.Task
2024-10-29 07:22:04 +01:00
syncRepo storage.Sync
localID int
2024-10-07 09:34:17 +02:00
}
2024-12-24 08:00:23 +01:00
func NewDelete(localIDRepo storage.LocalID, taskRepo storage.Task, syncRepo storage.Sync) Command {
2024-10-29 07:22:04 +01:00
return &Delete{
localIDRepo: localIDRepo,
2024-12-24 08:00:23 +01:00
taskRepo: taskRepo,
2024-10-29 07:22:04 +01:00
syncRepo: syncRepo,
2024-10-07 09:34:17 +02:00
}
}
2024-10-29 07:22:04 +01:00
func (del *Delete) Execute(main []string, flags map[string]string) error {
if len(main) < 2 || main[0] != "delete" {
return ErrWrongCommand
}
localID, err := strconv.Atoi(main[1])
if err != nil {
return fmt.Errorf("not a local id: %v", main[1])
}
del.localID = localID
return del.do()
}
func (del *Delete) do() error {
2024-10-07 09:34:17 +02:00
var id string
2024-10-29 07:22:04 +01:00
idMap, err := del.localIDRepo.FindAll()
2024-10-07 09:34:17 +02:00
if err != nil {
return fmt.Errorf("could not get local ids: %v", err)
}
2024-12-24 08:00:23 +01:00
for tskID, lid := range idMap {
2024-10-29 07:22:04 +01:00
if del.localID == lid {
2024-12-24 08:00:23 +01:00
id = tskID
2024-10-07 09:34:17 +02:00
}
}
if id == "" {
return fmt.Errorf("could not find local id")
}
2024-12-24 08:00:23 +01:00
tsk, err := del.taskRepo.Find(id)
2024-10-07 11:11:18 +02:00
if err != nil {
2024-12-24 08:00:23 +01:00
return fmt.Errorf("could not get task: %v", err)
2024-10-07 11:11:18 +02:00
}
2024-12-24 08:00:23 +01:00
it, err := tsk.Item()
2024-10-07 11:11:18 +02:00
if err != nil {
2024-12-24 08:00:23 +01:00
return fmt.Errorf("could not convert task to sync item: %v", err)
2024-10-07 11:11:18 +02:00
}
2024-10-29 07:22:04 +01:00
it.Deleted = true
if err := del.syncRepo.Store(it); err != nil {
2024-10-07 11:11:18 +02:00
return fmt.Errorf("could not store sync item: %v", err)
}
2024-10-29 07:22:04 +01:00
if err := del.localIDRepo.Delete(id); err != nil {
return fmt.Errorf("could not delete local id: %v", err)
}
2024-12-24 08:00:23 +01:00
if err := del.taskRepo.Delete(id); err != nil {
return fmt.Errorf("could not delete task: %v", err)
2024-10-29 07:22:04 +01:00
}
2024-10-07 09:34:17 +02:00
return nil
}