package morningalarm import ( "encoding/json" "errors" "os" ) // addAlarm adds an alarm to the list of alarms and starts a cron job to fire it at the specified time func (ma *MorningAlarm) addAlarm(time, name string) (*alarm, error) { // Check if alarm already exists if ma.getAlarm(name) != nil { return nil, errors.New("Alarm with name " + name + " already exists") } alarm := alarm{ Name: name, Time: time, Disabled: false, } alarm.cronID, _ = ma.armAlarm(&alarm) ma.alarms = append(ma.alarms, alarm) return &alarm, nil } func (ma *MorningAlarm) getAlarm(name string) *alarm { for _, alarm := range ma.alarms { if alarm.Name == name { return &alarm } } return nil } // loadAlarmsFromFile loads the list of alarms from alarms.json into memory func (ma *MorningAlarm) loadAlarmsFromFile() 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 } err = json.Unmarshal(content, &ma.alarms) if err != nil { return err } return nil } // saveAlarmsToFile saves the list of alarms to alarms.json func (ma *MorningAlarm) saveAlarmsToFile() 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 } // removeAlarm removes an alarm from the list of alarms and stops cron from firing it. Returns true if the alarm was removed, false if it was not found func (ma *MorningAlarm) removeAlarm(name string) bool { for _, alarm := range ma.alarms { if alarm.Name == name { // Stop cron from firing the alarm ma.disarmAlarm(&alarm) // Remove alarm from list of alarms 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 } // armAllAlarms arms all alarms in the list of alarms that are not disabled and returns an error if any of them fail to arm func (ma *MorningAlarm) armAllAlarms() error { for _, alarm := range ma.alarms { if !alarm.Disabled { id, err := ma.armAlarm(&alarm) if err != nil { return err } alarm.cronID = id } } return nil } // setDisabled sets the disabled status of an alarm func (ma *MorningAlarm) setDisabled(name string, disabled bool) { for i, alarm := range ma.alarms { if alarm.Name == name { if alarm.Disabled == disabled { return } ma.alarms[i].Disabled = disabled if disabled { ma.disarmAlarm(&alarm) } else { id, _ := ma.armAlarm(&alarm) ma.alarms[i].cronID = id } return } } }