using AlarmInfoServerSim.Services;
using CommunityToolkit.Mvvm.ComponentModel;

namespace AlarmInfoServerSim.ViewModels;

public partial class StatusBarViewModel : ObservableObject
{
    private readonly ILogService _logService; 
    private readonly ISharedConfig _sharedConfig;
    private readonly IInfoSendingService _infoSendingService;

    [ObservableProperty]
    private string _localIp;

    [ObservableProperty]
    private string _localPort;

    [ObservableProperty]
    private string _remoteIp;

    [ObservableProperty]
    private string _remotePort;

    [ObservableProperty]
    private string _status;

    public StatusBarViewModel(ILogService logService, ISharedConfig sharedConfig, IInfoSendingService sendInfoService)
    {
        _logService = logService;
        _sharedConfig = sharedConfig;
        _infoSendingService = sendInfoService;
        _infoSendingService.ConnectionChanged += OnConnectionChanged;

        _localIp = _sharedConfig.BasicInfo!.RTServerAddress!;
        _localPort = _sharedConfig.BasicInfo!.RTServerPort!.ToString();
        _remoteIp = "Unknown";
        _remotePort = "Unknown";
        _status = "Disconnected";


    }

    private void OnConnectionChanged(object? sender, (bool, UniversalNetFrame451.IO.TcpConnection) e)
    {
        App.Current.Dispatcher.Invoke(() =>
        {
            if (e.Item1)
            {
                Status = "Connected";
                RemoteIp = e.Item2.RemoteEndPoint.Address.ToString();
                RemotePort = e.Item2.RemoteEndPoint.Port.ToString();
                _logService.Log($"Get a connection from {RemoteIp}:{RemotePort}");
            }
            else
            {
                Status = "Disconnected";
                RemoteIp = "Unknown";
                RemotePort = "Unknown";
                _logService.Log($"The connection lost");
            }
        });
    }
}
