You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

87 lines
2.3 KiB

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using S22.Xmpp;
namespace RhinoReminds
{
public delegate void OnReminderListUpdateHandler(object sender, Reminder newReminder);
public class ReminderList
{
private int nextId = 0;
private readonly object saveLock = new object();
public SortedList<DateTime, Reminder> Reminders = new SortedList<DateTime, Reminder>();
public event OnReminderListUpdateHandler OnReminderListUpdate;
public ReminderList() {
}
public Reminder CreateReminder(Jid inJid, DateTime time, string message) {
Reminder result = new Reminder(nextId++, $"{inJid.Node}@{inJid.Domain}", time, message);
Console.WriteLine($"[Rhino/ReminderList] Created reminder {result}");
Reminders.Add(time, result);
OnReminderListUpdate(this, result);
return result;
}
public void Save(string filename)
{
// Make sure that the reminder thread doesn't try to save the reminders at the exact same time
// we receive a request for a new reminder
lock (saveLock) { // FUTURE: We could go lockless here with some work, but it's not worth it for the teeny chance & low overhead
XmlWriter xml = XmlWriter.Create(
filename,
new XmlWriterSettings() { Indent = true }
);
xml.WriteStartDocument();
xml.WriteStartElement("ReminderList");
xml.WriteElementString("NextId", nextId.ToString());
xml.WriteStartElement("Reminders");
foreach (Reminder nextReminder in Reminders.Values)
nextReminder.WriteToXml(xml);
xml.WriteEndElement();
xml.WriteEndElement();
xml.WriteEndDocument();
xml.Close();
}
}
public Reminder GetNextReminder()
{
if (Reminders.Count == 0)
return null;
return Reminders.Values[0];
}
public void DeleteReminder(Reminder nextReminder) {
Reminders.Remove(nextReminder.Time);
}
public static ReminderList FromXmlFile(string filepath)
{
XmlDocument xml = new XmlDocument();
xml.Load(filepath);
ReminderList result = new ReminderList();
result.nextId = int.Parse(xml.GetElementsByTagName("NextId")[0].InnerText);
foreach (XmlNode reminderXML in xml.GetElementsByTagName("Reminders")[0].ChildNodes) {
Reminder nextReminder = Reminder.FromXml(reminderXML);
result.Reminders.Add(nextReminder.Time, nextReminder);
}
return result;
}
}
}