gime-flat/model.go

128 lines
2.5 KiB
Go
Raw Normal View History

2018-08-02 20:05:31 +00:00
package main
import (
"encoding/json"
"fmt"
"strconv"
"time"
scribble "github.com/nanobox-io/golang-scribble"
)
func SaveTimer(entry *Timer) error {
db, err := scribble.New(cfg.Get("dbdir"), nil)
if err != nil {
fmt.Println(err.Error())
}
yr := strconv.Itoa(entry.GetStart().Year())
key := entry.GetUUID()
// Make sure that this entry isn't saved anywhere
db.Delete("active", key)
db.Delete(yr, key)
// Now write it
if entry.IsActive() {
if err = db.Write("active", key, entry); err != nil {
return err
}
} else {
if err = db.Write(yr, key, entry); err != nil {
// Error writing the time entry, don't edit metadata
return err
}
}
var m *Meta
m, err = LoadMetadata()
if err != nil {
m = new(Meta)
}
m.AddYear(entry.GetStart().Year())
m.AddTags(entry.GetTags())
return SaveMetadata(m)
}
func LoadTimer(uuid string) *Timer {
db, err := scribble.New(cfg.Get("dbdir"), nil)
timer := Timer{}
// Find the timer, see if it's active first
if err := db.Read("active", uuid, &timer); err == nil {
return &timer
}
// Ok, we have to check the years
var m *Meta
if m, err = LoadMetadata(); err != nil {
// Couldn't load the metadata...
return nil
}
for _, v := range m.Years {
if err = db.Read(strconv.Itoa(v), uuid, &timer); err == nil {
return &timer
}
}
// Didn't find it
return nil
}
func DeleteTimer(uuid string) error {
db, err := scribble.New(cfg.Get("dbdir"), nil)
if err != nil {
return err
}
tmr := LoadTimer(uuid)
if tmr.IsActive() {
return db.Delete("active", uuid)
}
yr := strconv.Itoa(tmr.GetStart().Year())
return db.Delete(yr, uuid)
}
func LoadActiveTimers() []Timer {
return LoadTimersFromDb("active")
}
func LoadTimers(st, end time.Time) []Timer {
var ret []Timer
stYr := st.Year()
endYr := end.Year()
m, err := LoadMetadata()
if err != nil {
return ret
}
for i := stYr; i <= endYr; i++ {
if m.HasYear(i) {
tmrs := LoadTimersFromDb(strconv.Itoa(i))
for _, v := range tmrs {
if v.GetStart().After(st) && v.GetStart().Before(end) {
ret = append(ret, v)
}
}
}
}
return ret
}
func LoadTimersFromDb(coll string) []Timer {
db, _ := scribble.New(cfg.Get("dbdir"), nil)
raw, _ := db.ReadAll(coll)
var timers []Timer
for _, tmr := range raw {
t := Timer{}
json.Unmarshal([]byte(tmr), &t)
timers = append(timers, t)
}
return timers
}
func FilterTimers(tmrs []Timer, filter func(t *Timer) bool) []Timer {
var ret []Timer
for _, v := range tmrs {
if filter(&v) {
ret = append(ret, v)
}
}
return ret
}