using ESBasic;
using Newtonsoft.Json;
using OMCS;
using OMCS.Passive;
using OMCS.Passive.MultiChat;
using OVCS.Core;
using System;
using System.Diagnostics;
using System.Text;
using System.Windows;

namespace OVCS.ClientWpf
{
    /// <summary>
    /// OVCS多人会议室 包括多人视频语音聊天、电子白板、共享远程桌面、文本聊天。
    /// </summary>
    public partial class MainWindow : Window
    {
        private IMultimediaManager multimediaManager; 
        private string roomId;  //房间号
        private bool isActiveDisconnect = false;
        private IChatGroup chatGroup;
        public MainWindow(string _roomId,IMultimediaManager _multimediaManager)
        {
            InitializeComponent();            
            this.roomId = _roomId;
            this.Title += this.roomId; 
            this.multimediaManager = _multimediaManager;
            this.multimediaManager.OutputVideo = true;
            this.multimediaManager.OutputAudio = false;
            this.multimediaManager.Mute = false;

            this.multimediaManager.ConnectionInterrupted += MultimediaManager_ConnectionInterrupted;
            this.multimediaManager.CustomizedMessageReceived += MultimediaManager_CustomizedMessageReceived;

            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.textChatContainer1.Initialize(this.roomId,  this.multimediaManager);
            this.Loaded += MainWindow_Loaded;
            this.Closing += MainWindow_Closing;
        }



        private void MultimediaManager_ConnectionInterrupted(System.Net.IPEndPoint obj)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<System.Net.IPEndPoint>(this.MultimediaManager_ConnectionInterrupted), obj);
            }
            else
            {
                //    if (isActiveDisconnect)
                //    {
                //        return;
                //    }
                MessageBox.Show("您已掉线！");
                this.Close();
            }
        }

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

        /// <summary>
        /// 设置扩展信息
        /// </summary>
        private void HandleGroupExtension(GroupExtension groupExtension)
        {
            //初始化
            this.multiVideoChatContainer1.Initialize(this.multimediaManager, this.roomId, groupExtension);
        }

        /// <summary>
        /// 在其他地方登录
        /// </summary>
        private void BasicOutter_BeingPushedOut()
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric(this.BasicOutter_BeingPushedOut));
            }
            else
            {
                this.isActiveDisconnect = true;
                MessageBox.Show("您已在其他地方登录！");
                this.Close();
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //加入会议时默认系统消息
            this.textChatContainer1.AddSystemMessage(string.Format("欢迎{0}进入会议", this.multimediaManager.CurrentUserID));
        }
        //页面关闭
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.isActiveDisconnect = true;
            this.multiVideoChatContainer1.Close();
            this.multimediaManager.Dispose(); 
            Process.GetCurrentProcess().Kill();
            Environment.Exit(0);
        } 

        #region 成员加入、退出会议室   

        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(IChatUnit obj)
        {
            string msg1 = string.Format("{0}加入会议", obj.MemberID);
            this.textChatContainer1.AddSystemMessage(msg1);
        }

        #endregion

        #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)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.BeginInvoke(new CbGeneric<string,int, byte[], string>(this.MultimediaManager_CustomizedMessageReceived), destID, chatType, data, tag);
            }
            else
            {
                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 = BitConverter.ToBoolean(data, 0);
                            if (isShare)
                            {
                                this.multiVideoChatContainer1.OpenRemotingDesktop(strings[1]);
                            }
                            else
                            {
                                this.multiVideoChatContainer1.CloseRemotingDesktop();
                            }
                            return;
                        }
                        #endregion
                        #region 白板消息的处理
                        if (chatType == InformationTypes.BroadcastWhiteBoard)
                        {
                            bool isShare = BitConverter.ToBoolean(data, 0);
                            if (isShare)
                            {
                                this.multiVideoChatContainer1.OpenRemotingWhiteBoard(this.roomId);
                            }
                            else
                            {
                                this.multiVideoChatContainer1.CloseRemotingWhiteBoard();
                            }
                            return;
                        }
                        #endregion
                        #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.CameraIndexChange(strings[1]);
                        }
                        #endregion
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                }
            }
        }

        #endregion

        #region CameraIndexChange

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

        #endregion


        //录制前后改变窗口状态
        internal void SetRecordingState(bool isRecord)
        {
            if (isRecord)
            {
                this.MaxHeight = this.Height;
                this.MaxWidth = this.Width;
                this.MinHeight = this.Height;
                this.MinWidth = this.Width;
                this.ResizeMode = ResizeMode.NoResize;
            }
            else
            {
                this.ResizeMode = ResizeMode.CanResize;
                this.MaxHeight = SystemParameters.PrimaryScreenHeight;
                this.MaxWidth = SystemParameters.PrimaryScreenWidth;
                this.MinHeight = 720; 
                this.MinWidth = 1188;
            }
        }


        #region SendCameraIndexChange

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

        #endregion
    }
}
