using CommunityToolkit.Mvvm.ComponentModel;
using PLCIOPointTool.Services;
using System.Collections.ObjectModel;

namespace PLCIOPointTool.ViewModels;

public partial class LogBarViewModel : ObservableObject, IDisposable
{
    private readonly ILogService _logService;

    private const int MaxLogCount = 100;

    private bool disposedValue;

    [ObservableProperty]
    private ObservableCollection<string> _logs = [];

    public LogBarViewModel(ILogService logService)
    {
        _logService = logService;
        _logService.MessageReceived += OnMessageReceived;
    }

    private void OnMessageReceived(object? sender, LogEventArgs e)
    {
        App.Current.Dispatcher.BeginInvoke(() =>
        {
            if (Logs.Count >= MaxLogCount)
            {
                Logs.RemoveAt(Logs.Count - 1);
            }

            Logs.Insert(0, $"[{e.LogTime}] [{e.LogType}] [{e.Message}]");
        });
    }

    #region Dispose
    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects)
                _logService.MessageReceived -= OnMessageReceived;
                Logs.Clear();
            }

            // TODO: free unmanaged resources (unmanaged objects) and override finalizer
            // TODO: set large fields to null
            disposedValue = true;
        }
    }

    // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
    // ~OutputBarViewModel()
    // {
    //     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
    //     Dispose(disposing: false);
    // }

    public void Dispose()
    {
        // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }
    #endregion
}
