using ESBasic;
using System.Windows;
using System.Windows.Controls;

namespace OVCS.ClientWpf.Tools
{
    /// <summary>
    /// AutoScaleContainer.xaml 的交互逻辑
    /// </summary>
    public partial class AutoScaleContainer : UserControl
    {
        private Size standardSize;
        private WrapPanel flowLayoutPanel;

        public WrapPanel FlowLayoutPanel
        {
            get { return flowLayoutPanel; }
        }
        public AutoScaleContainer()
        {
            InitializeComponent();
            this.flowLayoutPanel = this.wrapPanel;
            this.Loaded += AutoScaleContainer_Loaded;
        }
        /// <summary>
        /// 窗口尺寸修改后触发，参数：Size - 新的尺寸
        /// </summary>
        public event CbGeneric<Size> videoPanelSizeChange;
        private void AutoScaleContainer_Loaded(object sender, RoutedEventArgs e)
        {
            this.SetStandardSize(new Size(32, 19));
            this.UserControl_SizeChanged(null,null);
        }

        //设置等比缩放
        private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {

            if (this.wrapPanel == null)
            {
                return;
            }

            float wCoef = (float)(this.Width / (float)this.standardSize.Width);
            float hCoef = (float)(this.Height / (float)this.standardSize.Height);
            if (wCoef == hCoef)
            {
                this.wrapPanel.Width = this.Width;
                this.wrapPanel.Height = this.Height;
                this.videoPanelSizeChange?.Invoke(new Size(this.wrapPanel.Width, this.wrapPanel.Height));
                return;
            }

            if (wCoef < hCoef)
            {
                int newHeight = (int)(wCoef * this.standardSize.Height);
                this.wrapPanel.Width = this.Width;
                this.wrapPanel.Height = newHeight;
                this.videoPanelSizeChange?.Invoke(new Size(this.wrapPanel.Width, this.wrapPanel.Height));
                return;
            }
            int newWidth = (int)(hCoef * this.standardSize.Width);
            if(newWidth< 0)
            {
                return;
            }
            this.wrapPanel.Width = newWidth;
            this.wrapPanel.Height = this.Height;
            this.videoPanelSizeChange?.Invoke(new Size(this.wrapPanel.Width, this.wrapPanel.Height));
        }
        
        /// <summary>
        /// 设置标准尺寸。
        /// </summary>        
        /// <param name="_standardSize">用于等比缩放进行参考的标准尺寸</param>
        public void SetStandardSize(Size _standardSize)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<Size>(SetStandardSize), _standardSize);
            }
            else
            {
                this.standardSize = _standardSize;
            }
        }
    }
}
