using System.Threading.Tasks;

namespace WorkFlowCheck.MAUI.Pages.NFC;

public partial class NFCWaiter : ContentPage
{
    private bool _nfcIsActive = false;
    private TaskCompletionSource<string> _taskCompletionSource = new();

    public static async Task<string> ShowModalAsync()
    {
        var page = new NFCWaiter();
        await Shell.Current.Navigation.PushModalAsync(page);
        return await page._taskCompletionSource.Task;
    }

    public NFCWaiter()
    {
        InitializeComponent();
    }
    
    protected override async void OnAppearing()
    {
        base.OnAppearing();
#if ANDROID
        if (Platform.CurrentActivity is Android.App.Activity activity && activity is MainActivity mainActivity)
        {
            mainActivity.StartNfc(OnTagRead);
            _nfcIsActive = true;
        }
#endif

        await MainThread.InvokeOnMainThreadAsync(async () =>
        {
            await Task.Delay(TimeSpan.FromSeconds(30));
            Finish(null);
        });


    }
    
    protected override void OnDisappearing()
    {
        
#if ANDROID
        if (Platform.CurrentActivity is Android.App.Activity activity && activity is MainActivity mainActivity)
        {
            mainActivity.StopNfc();
        }
#endif
        base.OnDisappearing();
    }
    
    private void OnTagRead(string tagId)
    {
        Finish(tagId);
    }

    private async void Finish(string tagId)
    {
#if ANDROID
        if (Platform.CurrentActivity is Android.App.Activity activity && activity is MainActivity mainActivity)
        {
            if (_nfcIsActive)
            {
                mainActivity.StopNfc();
                _nfcIsActive = false;
            }
        }
#endif

        if (!_taskCompletionSource.Task.IsCompleted)
            _taskCompletionSource.SetResult(tagId);

        if (Navigation.ModalStack.Count > 0)
        {
            await Shell.Current.Navigation.PopModalAsync();
        }

        
    }

    




}