66 lines
1.8 KiB
C#
66 lines
1.8 KiB
C#
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
|
|
public sealed class HistoryTimeline
|
|
{
|
|
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
|
{
|
|
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
{
|
|
list = [];
|
|
_entityTimelines[entityId] = list;
|
|
}
|
|
|
|
list.AddRange(entries);
|
|
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
|
}
|
|
|
|
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
|
{
|
|
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
HistoryStateEntry? best = null;
|
|
foreach (var entry in entries)
|
|
{
|
|
if (entry.LastChanged <= timestamp)
|
|
{
|
|
best = entry;
|
|
}
|
|
else
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
|
|
{
|
|
var timestamps = new SortedSet<DateTimeOffset>();
|
|
|
|
foreach (var entries in _entityTimelines.Values)
|
|
{
|
|
foreach (var entry in entries)
|
|
{
|
|
timestamps.Add(entry.LastChanged);
|
|
}
|
|
}
|
|
|
|
return [.. timestamps];
|
|
}
|
|
|
|
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
|
|
|
|
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
|
|
{
|
|
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
|
|
}
|
|
|
|
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
|
|
}
|