using Serilog.Core;
using Serilog.Events;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace GUI.ViewModels;

public class LoggingCollection : ILogEventSink
{
  public int Capacity { get; }

  public ObservableCollection<LogMessage> Items { get; }

  public LoggingCollection(int capacity)
  {
    Capacity = capacity;
    Items = new ObservableCollection<LogMessage>(new List<LogMessage>(capacity));
  }

  public void Trim(int offset = 0)
  {
    for (int i = Items.Count - Capacity - offset; i >= 0; i--)
    {
      Items.RemoveAt(0);
    }
  }

  #region Implementation of ILogEventSink

  /// <inheritdoc />
  public void Emit(LogEvent logEvent)
  {
    Trim(1);

    Items.Add(new LogMessage
    {
      Timestamp = logEvent.Timestamp.DateTime,
      Message = logEvent.RenderMessage()
    });
  }

  #endregion
}