using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Txgy.EWS.Client.Common.Helpers
{
    public class VisualHost : Canvas
    {
        public List<Visual> visuals = new List<Visual>();

        //获取Visual的个数
        protected override int VisualChildrenCount
        {
            get { return visuals.Count; }
        }

        //获取Visual
        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }

        //添加Visual
        public void AddVisual(Visual visual)
        {
            InvokeOnDispatcher(() =>
            {
                if (visual == null)
                {
                    return;
                }

                visuals.Add(visual);
                base.AddVisualChild(visual);
                base.AddLogicalChild(visual);
            });
        }

        //删除Visual
        public void RemoveVisual(Visual visual)
        {
            InvokeOnDispatcher(() =>
            {
                if (visual == null)
                {
                    return;
                }

                if (!visuals.Remove(visual))
                {
                    return;
                }

                base.RemoveVisualChild(visual);
                base.RemoveLogicalChild(visual);
            });
        }

        private void InvokeOnDispatcher(Action action)
        {
            var dispatcher = Dispatcher;
            if (dispatcher == null || dispatcher.HasShutdownStarted || dispatcher.HasShutdownFinished)
            {
                return;
            }

            if (dispatcher.CheckAccess())
            {
                action();
                return;
            }

            dispatcher.Invoke(action);
        }

        //命中测试
        public TaggedVisual GetVisual(Point point)
        {
            HitTestResult hitResult = VisualTreeHelper.HitTest(this, point);
            if (hitResult != null)
            {
                if (hitResult.VisualHit is TaggedVisual)
                {
                    return hitResult.VisualHit as TaggedVisual;
                }
            }
            return null;
        }
        //public DrawingVisual GetVisual(Point point)
        //{
        //    HitTestResult hitResult = VisualTreeHelper.HitTest(this, point);
        //    if (hitResult != null)
        //    {

        //    }
        //    return hitResult.VisualHit as DrawingVisual;
        //}
    }
}
