using CPF;
using CPF.Controls;
using CPF.Drawing;
using CPF.Reflection;
using CPF.Threading;
using ESBasic;
using OMCS;
using OMCS.Cpf;
using OMCS.Linux;
using OMCS.Passive;
using OMCS.Passive.MultiChat;
using OMCS.Passive.Video;
using OVCS.ClientLinux.Tools;
using System;
using static OVCS.ClientLinux.MultiVideoChatContainer;

namespace OVCS.ClientLinux
{
    [CPF.Design.DesignerLoadStyle("res://OVCS.ClientLinux/Resource/Stylesheet1.css")]//用于设计的时候加载样式
    public class VideoPanel : Control
    {
        private bool isInit;
        public VideoPanel() 
        { 
            this.InitializeComponent();
        }
        protected override void InitializeComponent()
        {
            if (isInit)
            {
                return;
            }
            isInit = true;
            MarginLeft = 2;
            MarginRight = 2;
            MarginBottom = 2;
            Height = 268;
            Width = 432;
            Children.Add(new Grid
            {
                Size = SizeField.Fill,
                RowDefinitions =
                {
                    new RowDefinition
                    {
                        Height = GridLength.Auto,
                    },
                    new RowDefinition
                    {
                        Height = GridLength.Star
                    }
                },
                Children =
                {
                    new Grid
                    {
                      MarginLeft = 0,
                      MarginBottom = 0,
                      Background = "#303030",
                      Width = "100%",
                      Height= 25,
                      ColumnDefinitions =
                      {
                          new ColumnDefinition
                          {
                              Width = GridLength.Star
                          },
                          new ColumnDefinition
                          {
                              Width = GridLength.Auto
                          },
                           new ColumnDefinition
                          {
                              Width = GridLength.Auto
                          },
                          new ColumnDefinition
                          {
                              Width = GridLength.Auto
                          },
                          new ColumnDefinition
                          {
                              Width = 70
                          },
                      },
                      Children =
                       {
                           new TextBlock
                           {
                                MarginLeft = 10,
                                MarginTop = 3,
                                MarginBottom = 3,
                                Text = "aa02",
                                Foreground = Color.White,
                                FontSize = 15,
                                Name = "toolStrip1",
                                PresenterFor = this,
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        0
                                    }
                                }
                           },
                           new TextBlock
                           {
                                Visibility= Visibility.Visible,
                                MarginRight = 10,
                                MarginTop = 3,
                                MarginBottom = 3,
                                Text = "",
                                Foreground = Color.Red,
                                FontSize = 12,
                                Name = "disConnectReason",
                                PresenterFor = this,
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        1
                                    }
                                }
                           },
                           new TextBlock
                           {
                                MarginRight = 10,
                                MarginTop = 3,
                                MarginBottom = 3,
                                Text = "640*480",
                                Foreground = Color.White,
                                FontSize = 12,
                                Name = "videoSizeShow",
                                PresenterFor = this,
                                Attacheds =
                                {
                                    {
                                        Grid.ColumnIndex,
                                        2
                                    }
                                }
                           },
                           new Picture
                           {
                               MarginRight = 3,
                               MarginTop = 3,
                               MarginBottom = 3,
                               Name = "pictureBox_Mic",
                               PresenterFor = this,
                               Source = CommonHelper.ResourcesCatalog + "micNor.png",
                               Stretch = Stretch.UniformToFill,
                               Height = 20,
                               Width = 20,
                               Attacheds =
                               {
                                   {
                                       Grid.ColumnIndex,
                                       3
                                   }
                               }
                           },
                           new ProgressBar
                           {
                               Name="decibelProgress",
                               PresenterFor= this,
                               CornerRadius = "0,0,0,0",
                               MarginLeft = 7,
                               MarginRight = 10,
                               Height = 7,
                               Maximum = 100,
                               Attacheds =
                               {
                                   {
                                       Grid.ColumnIndex,
                                       4
                                   }
                               }
                           }
                       },
                      Attacheds =
                      {
                          {
                              Grid.RowIndex,
                              0
                          }
                      }
                    },
                    new Grid
                    {
                        MarginTop = 0,
                        MarginLeft = 0,
                        MarginRight = 0,
                        MarginBottom = 0,
                        Children =
                        {
                            new CameraPanel
                            {
                                Size = SizeField.Fill,
                                MarginTop = 0,
                                MarginLeft = 0,
                                MarginRight = 0,
                                MarginBottom = 0,
                                Name="cameraPanel1",
                                Background="#222",
                                PresenterFor = this,
                                ClipToBounds= true,
                            }
                        },
                        Attacheds =
                        {
                            {
                                Grid.RowIndex,
                                1
                            }
                        }
                    }
                }
            }) ;

            if (!DesignMode)//设计模式下不执行，也可以用#if !DesignMode
            {
                SetComponent();
            }
        }

//#if !DesignMode //用户代码写到这里，设计器下不执行，防止设计器出错

        private CameraPanel cameraPanel1;
        public CameraPanel CameraPanel1
        {
            get { return cameraPanel1; }
        }
        private Picture pictureBox_Mic;
        private ProgressBar decibelProgress;
        private TextBlock toolStrip1;
        private TextBlock videoSizeShow;
        private TextBlock disConnectReason;
        private IChatUnit chatUnit;
        public IChatUnit ChatUnit
        {
            get { return chatUnit; }
        }
        private bool isMySelf = false; 

        //当前的用户id
        public string MemberID
        {
            get
            {
                if (this.chatUnit == null)
                {
                    return null;
                }
                return this.chatUnit.MemberID;
            }
        }

        //摄像头连接器
        public DynamicCameraConnector DynamicCameraConnector
        {
            get { return this.chatUnit.DynamicCameraConnector; }
        }

        /// <summary>
        /// 其他用户 摄像头开启或关闭
        /// </summary>
        public event CbGeneric<bool, IChatUnit> CameraStateChange;

        /// <summary>
        /// 状态改变触发 
        /// </summary>
        public event CbGeneric<string, string> ChangeState;

        /// <summary>
        /// 视频正常连接成功并输出显示时 触发该事件
        /// </summary>
        public event CbGeneric<int> VideoByCount;

        /// <summary>
        /// 视频连接成功触发
        /// </summary>
        public event CbGeneric<IChatUnit> VideoConnect;
        private void SetComponent()
        {
            cameraPanel1 = this.FindPresenterByName<CameraPanel>("cameraPanel1");
            pictureBox_Mic = this.FindPresenterByName<Picture>("pictureBox_Mic");
            toolStrip1 = this.FindPresenterByName<TextBlock>("toolStrip1");
            decibelProgress = this.FindPresenterByName<ProgressBar>("decibelProgress");
            videoSizeShow = this.FindPresenterByName<TextBlock>("videoSizeShow");
            disConnectReason = this.FindPresenterByName<TextBlock>("disConnectReason");
        }
        protected override void OnInitialized()
        {
            base.OnInitialized();
        }
        //用户代码


        /// <summary>
        /// 初始化成员视频显示控件。
        /// </summary>    
        public void Initialize(IChatUnit unit, bool myself)
        {
            try
            {
                this.chatUnit = unit;
                this.isMySelf = myself;

                this.toolStrip1.Text = this.chatUnit.MemberID;
                //初始化麦克风连接器            
                this.chatUnit.MicrophoneConnector.ConnectEnded += new CbGeneric<string, ConnectResult>(MicrophoneConnector_ConnectEnded);
                this.chatUnit.MicrophoneConnector.OwnerOutputChanged += new CbGeneric<string>(MicrophoneConnector_OwnerOutputChanged);

                if (!this.isMySelf)
                {
                    this.chatUnit.MicrophoneConnector.BeginConnect(unit.MemberID);
                }
                if (this.isMySelf)
                {
                    this.videoSizeShow.Visibility = Visibility.Collapsed;
                }
                //初始化摄像头连接器
                this.chatUnit.DynamicCameraConnector.SetViewer(this.cameraPanel1);
                this.chatUnit.DynamicCameraConnector.VideoDrawMode = VideoDrawMode.Fill;
                this.chatUnit.DynamicCameraConnector.ConnectEnded += new CbGeneric<string, ConnectResult>(DynamicCameraConnector_ConnectEnded);
                this.chatUnit.DynamicCameraConnector.OwnerOutputChanged += new CbGeneric<string>(DynamicCameraConnector_OwnerOutputChanged);
                this.chatUnit.DynamicCameraConnector.Disconnected += new CbGeneric<string, ConnectorDisconnectedType>(DynamicCameraConnector_Disconnected);
                this.chatUnit.DynamicCameraConnector.OwnerVideoSizeChanged += DynamicCameraConnector_OwnerVideoSizeChanged;
                this.chatUnit.DynamicCameraConnector.BeginConnect(unit.MemberID);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        private void DynamicCameraConnector_OwnerVideoSizeChanged(string ownerID, System.Drawing.Size size)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                if (ownerID == this.chatUnit.MemberID)
                {
                    this.videoSizeShow.Text = string.Format("{0}*{1}", size.Width, size.Height);
                }
            });
        }
        void DynamicCameraConnector_Disconnected(string ownerID, ConnectorDisconnectedType disconnectedType)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                this.ChangeState?.Invoke(ownerID, "摄像头连接断开");
                this.VideoByCount?.Invoke(-1);
                this.disConnectReason.Visibility = Visibility.Visible;
                this.disConnectReason.Text = disconnectedType.ToString();
            });
        }

        //好友启用或禁用摄像头
        void DynamicCameraConnector_OwnerOutputChanged(string ownerID)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                this.ShowCameraState(ownerID, this.chatUnit.DynamicCameraConnector.OwnerOutput);
                this.CameraStateChange?.Invoke(this.chatUnit.DynamicCameraConnector.OwnerOutput, this.chatUnit);
                this.VideoByCount?.Invoke(this.chatUnit.DynamicCameraConnector.OwnerOutput ? 1 : -1);
            });
        }

        private ConnectResult cameraConnectResult;
        public ConnectResult CameraConnectResult
        {
            get { return cameraConnectResult; }
        }
        //摄像头连接器尝试连接的结果
        void DynamicCameraConnector_ConnectEnded(string ownerID, ConnectResult res)
        {
            UiSafeInvoker.ActionOnUI(()=>
            { 
                if (res == ConnectResult.Succeed)
                {
                    if (this.chatUnit.DynamicCameraConnector.OwnerMachineType == MachineType.Android || this.chatUnit.DynamicCameraConnector.OwnerMachineType == OMCS.Passive.Video.MachineType.IOS)
                    {
                        this.chatUnit.DynamicCameraConnector.VideoDrawMode = VideoDrawMode.Scale;
                    }
                    this.videoSizeShow.Text = string.Format("{0}*{1}", this.chatUnit.DynamicCameraConnector.VideoSize.Width, this.chatUnit.DynamicCameraConnector.VideoSize.Height);
                    this.VideoByCount?.Invoke(this.chatUnit.DynamicCameraConnector.OwnerOutput ? 1 : -1);
                    this.VideoConnect?.Invoke(this.chatUnit);
                }
                else
                {
                    this.VideoByCount?.Invoke(-1);
                }
                this.cameraConnectResult = res;
                this.ShowCameraState(ownerID, this.chatUnit.DynamicCameraConnector.OwnerOutput);
            });
        }

        /// <summary>
        /// 综合显示摄像头的状态。
        /// </summary>
        private void ShowCameraState(string ownerID, bool isCameraOutput)
        {
            if (this.cameraConnectResult != ConnectResult.Succeed)
            {

            }
            else
            {
                if (!isMySelf)
                {
                    this.ChangeState?.Invoke(ownerID, isCameraOutput ? "开启摄像头" : "关闭摄像头");
                    if (this.chatUnit.Tag != null)
                    {
                        ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.cameraVisibilityChange(isCameraOutput);
                    }
                    if (isCameraOutput)
                    {
                        this.disConnectReason.Visibility = Visibility.Collapsed;
                    }
                }

                if (!this.chatUnit.DynamicCameraConnector.OwnerOutput)
                {
                    return;
                }
            }
        }

        //好友启用或禁用麦克风
        void MicrophoneConnector_OwnerOutputChanged(string ownerID)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                this.ShowMicState(ownerID,this.chatUnit.MicrophoneConnector.OwnerOutput);
                if (!this.chatUnit.MicrophoneConnector.OwnerOutput)
                {
                    this.SpeakerDecibelChange(null);
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.SpeakerDecibelDownChange(null);
                }
            });
        }

        private ConnectResult connectMicResult;
        //麦克风连接器尝试连接的结果
        void MicrophoneConnector_ConnectEnded(string ownerID, ConnectResult res)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                this.connectMicResult = res;
                this.ShowMicState(ownerID, this.chatUnit.MicrophoneConnector.OwnerOutput);
            });
        }

        /// <summary>
        /// 综合显示麦克风的状态。
        /// </summary>
        public void ShowMicState(string ownerID,bool isMicOutput)
        {
            if (this.connectMicResult != ConnectResult.Succeed)
            {
                this.pictureBox_Mic.Visibility = Visibility.Visible;
                this.pictureBox_Mic.ToolTip = "主人麦克风无效";
                this.pictureBox_Mic.Source = ResourceManager.Singleton.MicUselessImage;
                if (this.chatUnit.Tag != null)
                {
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.PictureBox_Mic.Visibility = Visibility.Visible;
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.PictureBox_Mic.ToolTip = "主人麦克风无效";
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.PictureBox_Mic.Source = ResourceManager.Singleton.MicUselessImage;
                }
            }
            else
            {
                this.pictureBox_Mic.ToolTip = isMicOutput ? "主人麦克风开启" : "主人麦克风关闭";
                this.pictureBox_Mic.Source = isMicOutput ? ResourceManager.Singleton.MicEnableImage : ResourceManager.Singleton.MicDisableImage;
                if (this.chatUnit.Tag != null)
                {
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.PictureBox_Mic.ToolTip = isMicOutput ? "主人麦克风开启" : "主人麦克风关闭";
                    ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.PictureBox_Mic.Source = isMicOutput ? ResourceManager.Singleton.MicEnableImage : ResourceManager.Singleton.MicDisableImage;
                }
                if (!isMicOutput && this.isMySelf) {
                    this.SpeakerDecibelChange(null);
                    if (this.chatUnit.Tag != null)
                    {
                        ((VideoAllPanel)this.chatUnit.Tag).videoHidePanel.SpeakerDecibelDownChange(null);
                    }
                }
                if (!this.isMySelf)
                {
                    this.ChangeState?.Invoke(ownerID, isMicOutput ? "开启麦克风" : "关闭麦克风");
                }
            }
        }

        // 根据分贝值 渲染声音分贝律动条
        public void SpeakerDecibelChange(OMCS.Passive.Audio.UserDecibel userdecibel)
        {
            this.decibelProgress.Value = userdecibel != null ? userdecibel.Decibel : 0;
        }


        #region 摄像头索引改变时，重新调用BeginConnect

        internal void CameraIndexChange()
        {
            if (this.cameraConnectResult != ConnectResult.Succeed)
            {
                this.chatUnit.DynamicCameraConnector.BeginConnect(this.chatUnit.MemberID);
            }
        } 

        #endregion
    }
}
