using CPF;
using CPF.Controls;
using CPF.Drawing;
using Newtonsoft.Json;
using OMCS;
using OMCS.Cpf;
using OMCS.Passive;
using OVCS.ClientLinux.Tools;
using OVCS.LinuxCore;
using System;
using System.Diagnostics;
using System.Text;

namespace OVCS.ClientLinux
{
    public class MainWindow : Window
    {
        protected override void InitializeComponent()
        {
            LoadStyleFile("res://OVCS.ClientLinux/Stylesheet1.css");//加载样式文件，文件需要设置为内嵌资源
            Title = "OVCS视频会议系统2023";
            Background = Color.White;
            Height = 712;
            Width = 1188;
            MinHeight = 712;
            MinWidth = 1188;
            CanResize= true;
            Children.Add(new WindowFrame(this, new Panel
            {
                Size = SizeField.Fill,
                MarginTop = 0,
                MarginLeft = 0,
                MarginBottom = 0,
                MarginRight = 0,
                Children =
                {
                     Children.Add(new Grid
                     {
                        MarginTop = 0,
                        MarginLeft = 0,
                        MarginBottom = 0,
                        MarginRight = 0,
                        Size = SizeField.Fill,
                        ClipToBounds = true,
                        ColumnDefinitions =
                        {
                            new ColumnDefinition
                            {
                                Width = GridLength.Star
                            },
                            new ColumnDefinition
                            {
                                Width = GridLength.Auto
                            },
                        },
                        Children =
                        {
                            new MultiVideoChatContainer()
                            {
                                MarginTop = 0,
                                MarginLeft = 0,
                                MarginBottom = 0,
                                Name="multiVideoChatContainer1",
                                PresenterFor=this,
                                Attacheds=
                                {
                                    {
                                       Grid.ColumnIndex,
                                       0
                                    }
                                }
                            },
                            new TextChatContainer()
                            {
                                MarginTop = 0,
                                MarginRight = 0,
                                MarginBottom = 0,
                                Name = "textChatContainer1",
                                PresenterFor=this,
                                Attacheds=
                                {
                                    {
                                        Grid.ColumnIndex,
                                        1
                                    }
                                }
                            },
                        }
                    })
                   }
            })
            { 
                MaximizeBox = true,
                MinimizeBox= true,
                ShadowBlur= 0,
            }); 

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

        //#if !DesignMode //用户代码写到这里，设计器下不执行，防止设计器出错
        private IMultimediaManager multimediaManager; 
        private string roomId;  //房间号
        private bool isActiveDisconnect = false;
        private TextChatContainer textChatContainer1;
        private MultiVideoChatContainer multiVideoChatContainer1;
        private OMCS.Passive.MultiChat.IChatGroup chatGroup;


        private void SetComponent()
        {
            textChatContainer1 = this.FindPresenterByName<TextChatContainer>("textChatContainer1");
            multiVideoChatContainer1 = this.FindPresenterByName<MultiVideoChatContainer>("multiVideoChatContainer1");
            try
            {
                this.multimediaManager.OutputVideo = true;
                this.multimediaManager.OutputAudio = false;
                this.multimediaManager.Mute = false;

                //if (IsInitialized)
                //{
                 this.textChatContainer1.Initialize(this.roomId, this.multimediaManager);
                this.textChatContainer1.AddSystemMessage(string.Format("欢迎{0}进入会议", this.multimediaManager.CurrentUserID));
                //}
                //加入会议时默认系统消息
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "-" + ex.StackTrace);
            }
        }
        public MainWindow(string _roomId, IMultimediaManager _multimediaManager)
        {
            try
            {
                this.roomId = _roomId; 
                this.multimediaManager = _multimediaManager;
                this.multimediaManager.CustomizedMessageReceived += MultimediaManager_CustomizedMessageReceived;
                this.multimediaManager.ConnectionInterrupted += MultimediaManager_ConnectionInterrupted;


                this.chatGroup = this.multimediaManager.ChatGroupEntrance.Join(OMCS.Contracts.ChatType.Video, this.roomId);
                this.GetGroupExtension();
                this.chatGroup.SomeoneJoin += ChatGroup_SomeoneJoin;
                this.chatGroup.SomeoneExit += ChatGroup_SomeoneExit;
                 
        
                //    //扩展信息  
                //    //初始化
                this.Closed += MainWindow_Closed;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "-" + ex.StackTrace);
            }
        }

        private void ChatGroup_SomeoneExit(string memberID)
        {
            string msg1 = string.Format("{0}退出会议", memberID);
            this.textChatContainer1.AddSystemMessage(msg1);
            if (this.multiVideoChatContainer1.ShareDeskId == memberID)
            {
                this.multiVideoChatContainer1.ClearDesktopAndWhiteBoard(true);
            }
        }

        private void ChatGroup_SomeoneJoin(OMCS.Passive.MultiChat.IChatUnit unit)
        {
            string msg1 = string.Format("{0}加入会议", unit.MemberID);
            this.textChatContainer1.AddSystemMessage(msg1);
        }

        #region MultimediaManager_CustomizedMessageReceived

        /// <summary>
        /// 当收到来自服务器或其它客户端的自定义消息时触发
        /// </summary>
        /// <param name="destID">用户ID</param>
        /// <param name="chatType">消息类型</param>
        /// <param name="data">数据</param>
        /// <param name="tag">额外信息</param>
        private void MultimediaManager_CustomizedMessageReceived(string destID, int chatType, byte[] data, string tag)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                try
                {
                    string[] strings = tag.Split("-");
                    if (strings[0] == this.roomId)
                    {
                        #region 即时通信消息的处理
                        if (chatType == InformationTypes.BroadcastChat)
                        {
                            this.textChatContainer1.InsertMsg2ChatRoom(chatType, data);
                            return;
                        }
                        #endregion
                        #region 共享桌面消息的处理
                        if (chatType == InformationTypes.BroadcastShareDesk)
                        {
                            bool isShare = System.BitConverter.ToBoolean(data, 0);
                            if (isShare)
                            {
                                this.multiVideoChatContainer1.OpenRemotingDesktop(strings[1]);
                            }
                            else
                            {
                                this.multiVideoChatContainer1.CloseRemotingDesktop();
                            }
                            return;
                        }
                        #endregion
                        #region 白板消息的处理
                        if (chatType == InformationTypes.BroadcastWhiteBoard)
                        {
                            bool isShare = System.BitConverter.ToBoolean(data, 0);
                            if (isShare)
                            {
                                this.multiVideoChatContainer1.OpenRemotingWhiteBoard(this.roomId);
                            }
                            else
                            {
                                this.multiVideoChatContainer1.CloseRemotingWhiteBoard();
                            }
                            return;
                        }
                        #region 群组扩展信息
                        if (chatType == InformationTypes.GetGroupExtension)
                        {
                            string cont = Encoding.UTF8.GetString(data);
                            GroupExtension extension = JsonConvert.DeserializeObject<GroupExtension>(cont);
                            this.HandleGroupExtension(extension);
                        }
                        #endregion
                        #region 客户端的摄像头索引发生变化
                        if (chatType == InformationTypes.CameraIndexChanged)
                        { 
                            this.CameraDeviceChanged(strings[1]);
                        }
                        #endregion
                    }
                }
                catch (System.Exception ee)
                {
                    MessageBox.Show(ee.Message + " - " + ee.StackTrace);
                }
            });
        }

        #endregion

        #region CameraDeviceChanged

        private void CameraDeviceChanged(string destID)
        {
            this.multiVideoChatContainer1.CameraIndexChange(destID);
        }

        #endregion


        private void HandleGroupExtension(GroupExtension extension)
        { 
#if !DesignMode 
            this.multiVideoChatContainer1.Initialize(this.multimediaManager, this.roomId, extension, this);
#endif
        }

        private void MultimediaManager_ConnectionInterrupted(System.Net.IPEndPoint obj)
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                if (isActiveDisconnect)
                {
                    return;
                }
                MessageBox.Show("您已掉线！");
                this.Close();
            });
        }

        protected override void OnInitialized()
        {
            base.OnInitialized();
        }

        private WindowState lastWindowState = WindowState.Normal;
        protected override void OnPropertyChanged(string propertyName, object oldValue, object newValue, PropertyMetadataAttribute propertyMetadata)
        {
            base.OnPropertyChanged(propertyName, oldValue, newValue, propertyMetadata);
            if (propertyName.Contains("WindowState"))
            {
                lastWindowState = (WindowState)oldValue;
            }
            if (propertyName.Contains("ActualSize"))
            {
                if (this.WindowState == WindowState.Maximized || lastWindowState == WindowState.Maximized)
                {
                    this.multiVideoChatContainer1.SetUserControl_SizeChanged();
                }
            }
        }
        ////用户代码

        /// <summary>
        /// 获取扩展信息 
        /// </summary>
        private void GetGroupExtension()
        {
            this.multimediaManager.SendCustomizedMessage(null, InformationTypes.GetGroupExtension, null, this.roomId);
        }

        ///// <summary>
        ///// 掉线
        ///// </summary>
        private void Engine_ConnectionInterrupted()
        {
        }

        /// <summary>
        /// 在其他地方登录
        /// </summary>
        private void BasicOutter_BeingPushedOut()
        {
            UiSafeInvoker.ActionOnUI(delegate
            {
                this.isActiveDisconnect = true;
                MessageBox.Show("您已在其他地方登录！", "提示", this);
                this.Close();
            });
        }
        /// <summary>
        /// 页面关闭
        /// </summary>
        private void MainWindow_Closed(object sender, System.EventArgs e)
        {
            this.isActiveDisconnect = true;
            this.multimediaManager.Dispose(); 
            Process.GetCurrentProcess().Kill();
            System.Environment.Exit(0);
        }

        #region SendCameraIndexChange

        internal void SendCameraIndexChange()
        {
            if (this.multiVideoChatContainer1.myselfPanel.CameraConnectResult != ConnectResult.Succeed)
            { 
                this.multimediaManager.SendCustomizedMessage(null, InformationTypes.CameraIndexChanged, null, this.roomId);
                this.CameraDeviceChanged(this.multimediaManager.CurrentUserID);
            }
        }

        #endregion
    }
}
#endregion