using MultiLayout.UiModule;
using Misc;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Unity;
using System.ComponentModel;
using FObjBase;

namespace FLY.Thick.Base.UI.OnInit
{
    /// <summary>
    /// 虚拟键盘
    /// </summary>
    public class OnInitReboot : IOnInit,INotifyPropertyChanged
    {
        ParamDictionary paramDictionary;
        public OnInitReboot(ParamDictionary paramDictionary,int lv=1) 
        {
            this.paramDictionary = paramDictionary;
            Level = lv;
        }

        public int Level { get; }

        /// <summary>
        /// 自动重启电脑
        /// </summary>
        public bool IsAutoReboot { get; protected set; }

        /// <summary>
        /// 开机时间
        /// </summary>
        public int BootTimeMin { get; protected set; }

        public bool IsReBootAtOnce { get; set; }
        bool isRebooting = false;
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnInit()
        {
            IsAutoReboot = paramDictionary.GetValue(ParamDistItemKeys.AutoReboot, false);

            paramDictionary.ValueChanged += ParamDictionary_ValueChanged;

            PollModule.Current.Poll_Config(OnPoll, TimeSpan.FromMinutes(1));
        }

        private void ParamDictionary_ValueChanged(object sender, ParamDictionaryValueChangedEventArgs e)
        {
            if (e.Key == ParamDistItemKeys.AutoReboot)
            {
                IsAutoReboot = paramDictionary.GetValue(ParamDistItemKeys.AutoReboot, false);
            }
        }

        /// <summary>
        /// 1min 调用一次
        /// </summary>
        void OnPoll() 
        {
            BootTimeMin++;

            if (IsAutoReboot) 
            {
                if (IsReBootAtOnce && BootTimeMin > 1)
                {
                    reboot();
                }
                else if (BootTimeMin > 60 * 12)
                {
                    //12小时后， 到了中午12点，重启软件
                    if (DateTime.Now.Hour == 12)
                    {
                        reboot();
                    }
                }
            }

        }
        void reboot() 
        {
            if (!isRebooting)
            {
                isRebooting = true;

                //重启软件
                FLY.AppHelper.AppJustOne.Restart();
            }
        }
    }
}
