using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace FLY.FilmCasting.AutoDie.UI.Client.UiModule
{
    public class LongPress : INotifyPropertyChanged
    {


        /// <summary>
        /// 满9
        /// </summary>
        public int Progress { get; set; }

        public bool IsOK => (Progress == Max);

        public bool IsRunning => (Progress > 0);

        /// <summary>
        /// Progress 最大值
        /// </summary>
        public int Max { get; set; } = 360;

        /// <summary>
        /// 时间间隔
        /// </summary>
        public int IntervalMs { get; set; } = 2000;

        public RoutedEventHandler LongClick;

        private Stopwatch stopwatch = new Stopwatch();
        DispatcherTimer t = new DispatcherTimer();
        DispatcherTimer t_reset = new DispatcherTimer();

        public LongPress()
        {
            t.Tick += T_Tick;
            t.Interval = TimeSpan.FromSeconds(0.1);

            t_reset.Tick += T_reset_Tick;
            t.Interval = TimeSpan.FromSeconds(0.1);
        }

        private void T_reset_Tick(object sender, EventArgs e)
        {
            Reset();
            t_reset.Stop();
        }

        UIElement element;
        public void Init(UIElement element)
        {

            element.PreviewMouseDown += (s, e) => { button_MouseDown(); };
            element.PreviewTouchDown += (s, e) => { button_MouseDown(); };
            element.PreviewMouseUp += (s, e) => { button_MouseUp(); };
            element.PreviewTouchUp += (s, e) => { button_MouseUp(); };

            this.element = element;
        }

        public void button_MouseDown()
        {
            //必须点3秒
            Progress = 0;
            stopwatch.Restart();
            t.Start();
        }
        public void button_MouseUp()
        {
            t.Stop();
            t_reset.Start();
        }
        private void T_Tick(object sender, EventArgs e)
        {
            TimeSpan ts = stopwatch.Elapsed;

            double p = (double)(Max) * ts.TotalMilliseconds / IntervalMs;
            if (p >= Max)
            {
                Progress = Max;
                stopwatch.Stop();
                t.Stop();
                LongClick?.Invoke(element, null);
            }
            else
            {
                Progress = (int)p;
            }
        }



        public void Reset()
        {
            Progress = 0;
        }

        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion
    }

}
