using Avalonia.Threading;
using NP.Utilities;
using pavesys_iRAP.Helper;
using pavesys_iRAP.ViewModels;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace pavesys_iRAP.Business
{
    public class UserValidationScheduler
    {
        private readonly Timer _timer;
        private TimeSpan TimeSinceLastValidState;
        public MainWindowViewModel MainWindow { get; set; }
        

        public UserValidationScheduler(MainWindowViewModel _mainWindow)
        {
            MainWindow = _mainWindow;
            // Initialize the timer to run every 30 minutes
            _timer = new Timer(CheckUserValidity, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
        }

        private async void CheckUserValidity(object state)
        {


            if (AuthModule.accessToken == null || AuthModule.accessToken == string.Empty) 
                return; 
                            

            Debug.WriteLine(TimeSinceLastValidState.ToString());
            if (await AuthModule.CheckUserSession()) 
            {
                TimeSinceLastValidState = new();
                return;
            }
            TimeSinceLastValidState += TimeSpan.FromMinutes(1);


            if (!await AuthModule.CheckUserSession() && TimeSinceLastValidState == TimeSpan.FromMinutes(120))
            {
                MainWindow.Content = MainWindow.LoginPage;
                AuthModule.accessToken = string.Empty;
                AuthModule.isAdmin = false;
                TimeSinceLastValidState = new();
            }
            else if (TimeSinceLastValidState == TimeSpan.FromMinutes(30) )
            {
                Dispatcher.UIThread.Post(async () => await DialogHelper.ShowOkDialog("Warning", "Warn30"));
            }
            else if (TimeSinceLastValidState == TimeSpan.FromMinutes(60)) 
            {
                Dispatcher.UIThread.Post(async () => await DialogHelper.ShowOkDialog("Warning", "Warn60"));
            }
            else if (TimeSinceLastValidState == TimeSpan.FromMinutes(90)) 
            {
                Dispatcher.UIThread.Post(async () => await DialogHelper.ShowOkDialog("Warning", "Warn90"));
            }

        }
    }
}

