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

namespace AlarmInfoServerSim.ViewModels;

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

    private bool disposedValue;

    [ObservableProperty]
    private ObservableCollection<string> _logs;
    
    public LogBarViewModel(ILogService logService) 
    {
        _logService= logService;
        _logService.LogReceived += OnLogReceived;

        _logs = [];
    }

    private void OnLogReceived(object? sender, string e)
    {
        App.Current.Dispatcher.Invoke(() =>
        {
            if(Logs.Count>=50)
            {
                Logs.RemoveAt(Logs.Count - 1);
            }
            Logs.Insert(0, e);
        });
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                // TODO: dispose managed state (managed objects)
                _logService.LogReceived -= OnLogReceived;
            }

            // 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
    // ~LogBarViewModel()
    // {
    //     // 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);
    }
}
