using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using VIZ.Framework.Core;
using VIZ.Framework.Domain;

namespace VIZ.Framework.Common
{
    /// <summary>
    /// 时间控件
    /// </summary>
    public class TimeDisplayControl : TextBlock, IDisposable
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly static ILog log = LogManager.GetLogger(typeof(TimeDisplayControl));

        /// <summary>
        /// 时间控件
        /// </summary>
        public TimeDisplayControl()
        {
            ApplicationDomain.ObjectPoolManager.Add($"TimeDisplayControl__{Guid.NewGuid()}", this);

            this.Loaded += TimeDisplayControl_Loaded;
        }

        #region TimeStringFormat -- 时间字符串格式

        /// <summary>
        /// 时间字符串格式
        /// </summary>
        public string TimeStringFormat
        {
            get { return (string)GetValue(TimeStringFormatProperty); }
            set { SetValue(TimeStringFormatProperty, value); }
        }

        /// <summary>
        /// Using a DependencyProperty as the backing store for TimeStringFormat.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty TimeStringFormatProperty =
            DependencyProperty.Register("TimeStringFormat", typeof(string), typeof(TimeDisplayControl), new PropertyMetadata("yyyy-MM-dd HH:mm:ss"));

        #endregion

        /// <summary>
        /// 更新任务信息
        /// </summary>
        private TaskInfo updateTaskInfo;

        /// <summary>
        /// 更新任务
        /// </summary>
        private Task updateTask;

        /// <summary>
        /// 销毁
        /// </summary>
        public void Dispose()
        {
            if (this.updateTaskInfo == null)
                return;

            this.updateTaskInfo.IsCancel = true;
            this.updateTaskInfo = null;
            this.updateTask = null;
        }

        /// <summary>
        /// 控件完成加载
        /// </summary>
        private void TimeDisplayControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (this.updateTask != null)
                return;

            this.updateTaskInfo = new TaskInfo();
            this.updateTask = Task.Run(this.update);
        }

        /// <summary>
        /// 更新
        /// </summary>
        [DebuggerNonUserCode]
        private void update()
        {
            TaskInfo info = this.updateTaskInfo;
            if (info == null)
                return;

            while (!info.IsCancel)
            {
                WPFHelper.BeginInvoke(() =>
                {
                    this.Text = DateTime.Now.ToString(this.TimeStringFormat);
                });

                Task.Delay(1000).Wait();
            }
        }
    }
}
