package morningalarm import ( "encoding/json" "errors" "os" "time" "github.com/robfig/cron/v3" ) func (ma *MorningAlarm) nextAlarm() *time.Time { if len(ma.cr.Entries()) == 0 { return nil } min := ma.cr.Entries()[0].Next for _, entry := range ma.cr.Entries() { if entry.Next.Before(min) { min = entry.Next } } return &min } func (ma *MorningAlarm) addAlarm(spec string, name string) (cron.EntryID, error) { // Check if alarm already exists if ma.getAlarm(name) != nil { return 0, errors.New("Alarm already exists") } id, err := ma.cr.AddFunc(spec, ma.fireAlarm) if err != nil { return 0, err } ma.alarms = append(ma.alarms, alarm{ id: id, Time: spec, Name: name, }) return id, nil } func (ma *MorningAlarm) saveAlarms() error { content, err := json.Marshal(ma.alarms) if err != nil { return err } err = os.WriteFile("alarms.json", content, 0644) if err != nil { return err } return nil } func (ma *MorningAlarm) loadAlarms() error { if _, err := os.Stat("alarms.json"); os.IsNotExist(err) { ma.alarms = []alarm{} return nil } content, err := os.ReadFile("alarms.json") if err != nil { return err } var ent []alarm err = json.Unmarshal(content, &ent) if err != nil { return err } for _, entry := range ent { _, err := ma.addAlarm(entry.Time, entry.Name) if err != nil { return err } } return nil } func (ma *MorningAlarm) fireAlarm() { ma.playWakeUpMusic() } func (ma *MorningAlarm) getAlarm(name string) *alarm { for _, alarm := range ma.alarms { if alarm.Name == name { return &alarm } } return nil } func (ma *MorningAlarm) deleteAlarm(name string) bool { for _, alarm := range ma.alarms { if alarm.Name == name { ma.cr.Remove(alarm.id) for i, a := range ma.alarms { if a.Name == name { ma.alarms = append(ma.alarms[:i], ma.alarms[i+1:]...) break } } return true } } return false }