using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VIZ.Framework.Common
{
    /// <summary>
    /// 跟踪框扩展
    /// </summary>
    public static class TrackingBoxExpand
    {
        /// <summary>
        /// 更新跟踪框
        /// </summary>
        /// <param name="videoControl">视频控件</param>
        /// <param name="trackingBoxInfos">跟踪框信息</param>
        public static void UpdateTrackingBox(this VideoControl videoControl, List<TrackingBoxInfo> trackingBoxInfos)
        {
            if (videoControl.videoRender == null)
                return;

            TrackingBoxPlugin plugin = videoControl.GetPlugin<TrackingBoxPlugin>(VideoControlPluginNames.TrackingBox);
            if (plugin == null)
                return;

            plugin.Update(trackingBoxInfos);
        }

        /// <summary>
        /// 清理跟踪框
        /// </summary>
        /// <param name="videoControl">视频控件</param>
        public static void ClearTrackingBox(this VideoControl videoControl)
        {
            if (videoControl.videoRender == null)
                return;

            TrackingBoxPlugin plugin = videoControl.GetPlugin<TrackingBoxPlugin>(VideoControlPluginNames.TrackingBox);
            if (plugin == null)
                return;

            plugin.Update(null);
        }

        /// <summary>
        /// 命中测试
        /// </summary>
        /// <param name="trackingBoxInfos">跟踪框信息结合</param>
        /// <param name="point">视频坐标</param>
        /// <returns>命中的跟踪框</returns>
        public static TrackingBoxInfo HitTest(List<TrackingBoxInfo> trackingBoxInfos, System.Windows.Point point)
        {
            if (trackingBoxInfos == null || trackingBoxInfos.Count == 0)
                return null;

            TrackingBoxInfo result = null;
            double min = double.MaxValue;

            foreach (TrackingBoxInfo item in trackingBoxInfos)
            {
                System.Windows.Point center = new System.Windows.Point((item.SrcRect.Right - item.SrcRect.Left) / 2d + item.SrcRect.Left, (item.SrcRect.Bottom - item.SrcRect.Top) / 2d + item.SrcRect.Top);

                double dist = Math.Pow((point.Y - center.Y), 2) + Math.Pow((point.X - center.X), 2);
                if (dist < min)
                {
                    min = dist;
                    result = item;
                }
            }

            return result;
        }
    }
}
