aboutsummaryrefslogtreecommitdiffstats
path: root/todolist/file_store.go
blob: c7c23c73a722e833d9b86d23de65194434eb523a (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
118
119
120
121
122
123
124
125
126
127
128
package todolist

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/user"
	"sort"
)

type FileStore struct {
	FileLocation string
	Data         []*Todo
}

func NewFileStore() *FileStore {
	usr, _ := user.Current()
	return &FileStore{FileLocation: usr.HomeDir + "/.todos.json"}
}

func (f *FileStore) Add(todo *Todo) {
	todo.Id = f.NextId()
	f.Data = append(f.Data, todo)
}

func (f *FileStore) FindById(id int) *Todo {
	for _, todo := range f.Data {
		if todo.Id == id {
			return todo
		}
	}
	return nil
}

func (f *FileStore) Delete(id int) {
	i := -1
	for index, todo := range f.Data {
		if todo.Id == id {
			i = index
		}
	}

	f.Data = append(f.Data[:i], f.Data[i+1:]...)
}

func (f *FileStore) Complete(id int) {
	todo := f.FindById(id)
	todo.Completed = true
	f.Delete(id)
	f.Data = append(f.Data, todo)
}

func (f *FileStore) Uncomplete(id int) {
	todo := f.FindById(id)
	todo.Completed = false
	f.Delete(id)
	f.Data = append(f.Data, todo)
}

func (f *FileStore) Archive(id int) {
	todo := f.FindById(id)
	todo.Archived = true
	f.Delete(id)
	f.Data = append(f.Data, todo)
}

func (f *FileStore) Unarchive(id int) {
	todo := f.FindById(id)
	todo.Archived = false
	f.Delete(id)
	f.Data = append(f.Data, todo)
}

func (f *FileStore) IndexOf(todoToFind *Todo) int {
	for i, todo := range f.Data {
		if todo.Id == todoToFind.Id {
			return i
		}
	}
	return -1
}

func (f *FileStore) Load() {
	data, err := ioutil.ReadFile(f.FileLocation)
	if err != nil {
		fmt.Println("Error reading file", err)
		os.Exit(1)
	}

	jerr := json.Unmarshal(data, &f.Data)
	if jerr != nil {
		fmt.Println("Error reading json data", jerr)
		os.Exit(1)
	}
}

func (f *FileStore) Save() {
	data, _ := json.Marshal(f.Data)
	if err := ioutil.WriteFile(f.FileLocation, []byte(data), 0644); err != nil {
		fmt.Println("Error writing json file", err)
	}
}

type ByDate []*Todo

func (a ByDate) Len() int      { return len(a) }
func (a ByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByDate) Less(i, j int) bool {
	t1Due := a[i].CalculateDueTime()
	t2Due := a[j].CalculateDueTime()
	return t1Due.Before(t2Due)
}

func (f *FileStore) Todos() []*Todo {
	sort.Sort(ByDate(f.Data))
	return f.Data
}

func (f *FileStore) NextId() int {
	maxId := 0
	for _, todo := range f.Data {
		if todo.Id > maxId {
			maxId = todo.Id
		}
	}
	return maxId + 1
}