using Aitex.Core.Account;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace MECF.Framework.UI.Client.ClientBase.Dialog
{
    /// <summary>
    /// Interaction logic for LoginRequestWaitDialog.xaml
    /// </summary>
    public partial class LoginRequestWaitDialog : Window
    {
        #region Variables

        private readonly CancellationTokenSource _ctsCountDownTask;
        private readonly IProgress<double> _progCountDown;

        #endregion

        public LoginRequestWaitDialog()
        {
            InitializeComponent();

            _ctsCountDownTask = new CancellationTokenSource();

            _progCountDown = new Progress<double>(countDown =>
            {
                // 更新Cancel按钮倒计时数值
                // 如果倒计时为0，则关闭当前窗口
                if (countDown > 0)
                    BtnCancel.Content = $"Cancel ({countDown:F0}s)";
                else
                    Close();
            });
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            var closeTime = DateTime.Now.Add(TimeSpan.FromSeconds(CredentialManager.REQ_LOGIN_DIALOG_LIFT_TIME_SEC));
            var ct = _ctsCountDownTask?.Token;
            Task.Run(() =>
            {
                while (true)
                {
                    var timeRemained = (closeTime - DateTime.Now).TotalSeconds;
                    if (timeRemained <= 0)
                    {
                        // 关闭对话框
                        _progCountDown.Report(0);
                        break;
                    }

                    _progCountDown.Report(timeRemained);
                    
                    Thread.Sleep(500);

                    // 操作被取消
                    if (ct is { IsCancellationRequested: true })
                    {
                        // 关闭对话框
                        _progCountDown.Report(0);
                        break;
                    }
                }
            });
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
           Close();
        }
    }
}


