aboutsummaryrefslogtreecommitdiffstats
path: root/todolist/app.go
blob: 2af33619736c0b83cb00a3ed9874f0762cca5ed1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package todolist

import (
	"fmt"
	"regexp"
	"strconv"
)

type App struct {
	TodoStore Store
}

func NewApp() *App {
	app := &App{TodoStore: NewFileStore()}
	app.TodoStore.Load()
	return app
}

func (a *App) AddTodo(input string) {
	parser := &Parser{}
	todo := parser.ParseNewTodo(input)

	a.TodoStore.Add(todo)
	a.TodoStore.Save()
	fmt.Println("Todo added.")
}

func (a *App) DeleteTodo(input string) {
	id := a.getId(input)
	if id != -1 {
		a.TodoStore.Delete(id)
		a.TodoStore.Save()
		fmt.Println("Todo deleted.")
	} else {
		fmt.Println("Could not find id.")
	}
}

func (a *App) CompleteTodo(input string) {
	id := a.getId(input)
	if id != -1 {
		a.TodoStore.Complete(id)
		a.TodoStore.Save()
		fmt.Println("Todo completed.")
	} else {
		fmt.Println("Could not find id.")
	}
}

func (a *App) UncompleteTodo(input string) {
	id := a.getId(input)
	if id != -1 {
		a.TodoStore.Uncomplete(id)
		a.TodoStore.Save()
		fmt.Println("Todo uncompleted.")
	} else {
		fmt.Println("Could not find id.")
	}
}

func (a *App) ArchiveTodo(input string) {
	id := a.getId(input)
	if id != -1 {
		a.TodoStore.Archive(id)
		a.TodoStore.Save()
		fmt.Println("Todo archived.")
	} else {
		fmt.Println("Could not find id.")
	}
}

func (a *App) UnarchiveTodo(input string) {
	id := a.getId(input)
	if id != -1 {
		a.TodoStore.Unarchive(id)
		a.TodoStore.Save()
		fmt.Println("Todo unarchived.")
	} else {
		fmt.Println("Could not find id.")
	}
}

func (a *App) ListTodos(input string) {
	filtered := NewFilter(a.TodoStore.Todos()).Filter(input)
	grouped := a.getGroups(input, filtered)

	formatter := NewFormatter(grouped)
	formatter.Print()
}

func (a *App) getId(input string) int {

	re, _ := regexp.Compile("\\d+")
	if re.MatchString(input) {
		id, _ := strconv.Atoi(re.FindString(input))
		return id
	} else {
		return -1
	}
}

func (a *App) getGroups(input string, todos []Todo) *GroupedTodos {
	grouper := &Grouper{}
	contextRegex, _ := regexp.Compile(`by c.*$`)
	projectRegex, _ := regexp.Compile(`by p.*$`)

	var grouped *GroupedTodos

	if contextRegex.MatchString(input) {
		grouped = grouper.GroupByContext(todos)
	} else if projectRegex.MatchString(input) {
		grouped = grouper.GroupByContext(todos)
	} else {
		grouped = grouper.GroupByNothing(todos)
	}
	return grouped
}