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.
 
 
RhinoReminds/RhinoReminds/ReminderList.cs

108 lines
2.7 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}");
while (Reminders.ContainsKey(time))
time = time.AddMilliseconds(1);
Reminders.Add(time, result);
OnReminderListUpdate(this, result);
return result;
}
public Reminder GetNextReminder()
{
if (Reminders.Count == 0)
return null;
return Reminders.Values[0];
}
public Reminder GetById(int targetId)
{
return Reminders.First((KeyValuePair<DateTime, Reminder> nextPair) => nextPair.Value.Id == targetId).Value;
}
public void DeleteReminder(Reminder nextReminder)
{
Reminders.Remove(nextReminder.Time);
}
#region Persistence
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 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);
DateTime timeKey = nextReminder.Time;
while (result.Reminders.ContainsKey(timeKey))
timeKey = timeKey.AddMilliseconds(1);
result.Reminders.Add(timeKey, nextReminder);
}
return result;
}
#endregion
}
}