using System.Collections.ObjectModel;
using System.Windows.Input;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Pages.BaseStock.CheckPoints;
using WorkFlowCheck.MAUI.Services.Interfaces;
using Plugin.NFC;

namespace WorkFlowCheck.MAUI.Pages.BaseStock;

public partial class CheckPointsPage : ContentPage
{
    private readonly IBaseStockService _baseStockService;
    private readonly ISyncService _syncService;
    private bool _onReceiveing = false;

    public CheckPointsPage()
    {
        InitializeComponent();
        _baseStockService = MauiProgram.ServiceProvider.GetRequiredService<IBaseStockService>();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
    }

    public ICommand RefreshCommand { get; set; }
    public ICommand EditCommand { get; set; }
    public ICommand PairCommand { get; set; }
    public bool IsRefreshing { get; set; }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        RefreshCommand = new Command(async () => await LoadCheckPoints());
        EditCommand = new Command<CheckPointDTO>(OnEditItem);
        PairCommand = new Command<CheckPointDTO>(OnPairItem);

        BindingContext = this;
        await LoadCheckPoints();

    }
    private async Task LoadCheckPoints()
    {
        IsRefreshing = true;
        await _syncService.SyncDatas();
        CheckPointsList.ItemsSource = await _baseStockService.GetAllCheckPoints();
        IsRefreshing = false;
        OnPropertyChanged(nameof(IsRefreshing));
    }
    private async void OnEditItem(CheckPointDTO checkPointDTO)
    {
        // Navigálás a CheckPointEdit.xaml-ra, és átadjuk az editálni kívánt elemet
        await Navigation.PushAsync(new CheckPointEditPage(checkPointDTO));
    }
    private async void OnPairItem(CheckPointDTO checkPointDTO)
    {
        _checkPointDTO = checkPointDTO;
        await BeginListening();
    }
    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//BaseStockPage");
        return true;
    }

    #region NFC
    bool _eventsAlreadySubscribed = false;
    CheckPointDTO _checkPointDTO = null;
    async Task BeginListening()
    {
        try
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                SubscribeEvents();
                CrossNFC.Current.StartListening();
            });
        }
        catch (Exception ex)
        {

        }
    }
    async Task EndListening()
    {
        try
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                UnsubscribeEvents();
                CrossNFC.Current.StopPublishing();
                CrossNFC.Current.StopListening();
                
            });
        }
        catch (Exception ex)
        {

        }
    }
    void SubscribeEvents()
    {
        if (_eventsAlreadySubscribed)
            UnsubscribeEvents();

        _eventsAlreadySubscribed = true;
        CrossNFC.Current.OnMessageReceived += Current_OnMessageReceived_NFCData;
    }
    void UnsubscribeEvents()
    {
        CrossNFC.Current.OnMessageReceived -= Current_OnMessageReceived_NFCData;
        _eventsAlreadySubscribed = false;
    }
    async void Current_OnMessageReceived_NFCData(ITagInfo tagInfo)
    {
        if (_onReceiveing) return;
        _onReceiveing = true;   
        if (tagInfo == null)
        {
            return;
        }
        var identifier = tagInfo.Identifier;
        var serialNumber = NFCUtils.ByteArrayToHexString(identifier, ":");

        if (_checkPointDTO != null)
        {
            _checkPointDTO.Code = serialNumber;
            await _baseStockService.UpdateCheckPoint(_checkPointDTO);
            await Task.Delay(500);
            await EndListening();   
            await LoadCheckPoints();
        }
        _onReceiveing = false;  
    }

    #endregion
}