using ESBasic;
using ESBasic.ObjectManagement.Managers;
using ESBasic.Widget;
using ESFramework.Boost.WinForm;
using Newtonsoft.Json;
using OMCS.Passive;
using Oraycn.ChatRendering;
using OVCS.Core;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace OVCS
{
    public partial class TextChatControl : UserControl
    {       
        private EmotionForm emotionForm ;
        private string userID = "";
        private string groupID = "";
        private ObjectManager<string, ChatMessageRecord> chatMessageManager = new ObjectManager<string, ChatMessageRecord>();
        JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
        #region ButtonSend
        /// <summary>
        /// ButtonSend 用于设为AcceptButton
        /// </summary>
        public Button ButtonSend
        {
            get
            {
                return this.button_send;
            }
        }
        #endregion
        private IChatRender chatRender; 
        private static List<Image> imageEmojiList = new List<Image>();
        public static List<Image> ImageEmojiList
        {
            get
            {
                return imageEmojiList;
            }
        }

        private static Dictionary<string, Image> imageHeadList = new Dictionary<string, Image>();
        public static Dictionary<string, Image> ImageHeadList
        {
            get
            {
                return imageHeadList;
            }
        }
        private object locker = new object();
        private DateTime lastMessageTime = DateTime.MinValue;
        private IMultimediaManager multimediaManager;
        public TextChatControl()
        {
            InitializeComponent();
            jsonSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            this.fontDialog1.ShowColor = true;
            for (int i = 0; i < this.imageListEmoji.Images.Count; i++)
            {
                imageEmojiList.Add(this.imageListEmoji.Images[i]);
            }
            for (int i = 0; i < this.imageListHead.Images.Count; i++)
            {
                imageHeadList.Add((i + 1).ToString(), this.imageListHead.Images[i]);
            }
        }

        public void Initialize(string _userID, string groupID, IMultimediaManager _multimediaManager)
        {
            this.userID = _userID;
            this.groupID = groupID;
            this.multimediaManager = _multimediaManager;
            RenderSettings.TextFontSize = 10;
            this.chatRender = ChatRenderFactory.CreateChatRender(new RenderDataProvider(), this.chatBox_his, this.userID, this.groupID, true,WinRenderType.Winform);
            this.chatBox_his.Initialize(chatRender);
            #region Emotion
            List<string> tempList = ESBasic.Helpers.FileHelper.GetOffspringFiles(AppDomain.CurrentDomain.BaseDirectory + "Emotion\\");
            List<string> emotionFileList = new List<string>();
            foreach (string file in tempList)
            {
                string name = file.ToLower();
                if (name.EndsWith(".bmp") || name.EndsWith(".jpg") || name.EndsWith(".jpeg") || name.EndsWith(".png") || name.EndsWith(".gif"))
                {
                    emotionFileList.Add(name);
                }
            }
            emotionFileList.Sort(new Comparison<string>(CompareEmotionName));
            List<Image> emotionList = new List<Image>();
            for (int i = 0; i < emotionFileList.Count; i++)
            {
                emotionList.Add(Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Emotion\\" + emotionFileList[i]));
            }
            #endregion

            this.emotionForm = new EmotionForm();
            this.emotionForm.Load += new EventHandler(emotionForm_Load);
            this.emotionForm.Initialize(emotionList);
            this.emotionForm.EmotionClicked += new CbGeneric<int, Image>(emotionForm_Clicked);
            this.emotionForm.Visible = false;
            this.emotionForm.LostFocus += new EventHandler(emotionForm_LostFocus);
        }

        void emotionForm_LostFocus(object sender, EventArgs e)
        {
            this.emotionForm.Visible = false;
        }

        void emotionForm_Load(object sender, EventArgs e)
        {
            this.SetEmotionFormLocation();
        }

        private void SetEmotionFormLocation()
        {
            Point pt = this.PointToScreen(this.panel1.Location);
            Point pos = new Point(pt.X + 30 - (this.emotionForm.Width / 2), pt.Y - this.emotionForm.Height);

            if (pos.X < 10)
            {
                pos = new Point(10, pos.Y);
            }
            this.emotionForm.Location = pos;
        }

        void emotionForm_Clicked(int imgIndex, Image img)
        {
            this.emotionForm.Visible = false;
        }

        private static int CompareEmotionName(string a, string b)
        {
            if (a.Length != b.Length)
            {
                return a.Length - b.Length;
            }

            return a.CompareTo(b);
        }

       
       
        #region button_send_Click
        private void button_send_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.richTextBox_send.Text.Trim() == "")
                {
                    MessageBox.Show("请输入文本再发送");
                    return;
                }
                ChatMessageRecord contract = new ChatMessageRecord() { Guid = Guid.NewGuid().ToString(), SpeakerID = this.userID, ListenerID = this.userID, MessageTime = DateTime.Now, ChatMessageType = (int)ChatMessageType.TextEmotion };
                contract.ContentStr = this.richTextBox_send.Text;
                string cont = JsonConvert.SerializeObject(contract, Newtonsoft.Json.Formatting.None, this.jsonSerializerSettings);
                byte[] recordInfo = Encoding.UTF8.GetBytes(cont);
                this.AppendChatBoxContent(this.userID, contract, Color.SeaGreen);

                //广播消息给组友
                this.multimediaManager.SendCustomizedMessage(null, InformationTypes.BroadcastChat, recordInfo, this.groupID);               

                //清空输入框
                this.richTextBox_send.Clear();
                this.richTextBox_send.Focus();
            }
            catch (Exception ee)
            {
                Program.Logger.Log(ee, "TextChatControl.button_send_Click", ESBasic.Loggers.ErrorLevel.High);
                MessageBox.Show(ee.Message);
            }
        } 
        #endregion

        #region ShowOtherTextChat
        public void ShowOtherTextChat(string broadcastID, ChatMessageRecord content)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string, ChatMessageRecord>(this.ShowOtherTextChat), broadcastID, content);
            }
            else
            {
                this.AppendChatBoxContent(broadcastID, content, Color.Black);
            }
        } 
        #endregion

        private void AppendChatBoxContent(string userName, ChatMessageRecord content, Color color)
        {
            this.AppendSendTime(DateTime.Now);
            this.chatRender.AddChatItemText(content.Guid, content.SpeakerID, content.ContentStr);
            this.chatMessageManager.Add(content.Guid, content);
            this.chatBox_his.ScrollToBottom();
        }

        #region ShowSystemMessage
        public void ShowSystemMessage(string message)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string>(this.ShowSystemMessage), message);
            }
            else
            {
                this.AppendSendTime(DateTime.Now);
                this.chatRender.AddChatItemSystemMessage(message);
            }
        }
        #endregion

        #region ShowFileTransCompleted
        //internal void ShowFileTransCompleted(string projectName)
        //{
        //    if (this.InvokeRequired)
        //    {
        //        this.Invoke(new CbGeneric<string>(this.ShowFileTransCompleted), projectName);
        //    }
        //    else
        //    {
        //        DateTime showTime = DateTime.Now;
        //        this.agileRichTextBox_history.AppendRichText(string.Format("{0}  {1}\n", "系统", showTime), null, null, Color.DarkGray);
        //        string showText = string.Format("{0} {1}\n", projectName, "下载成功");
        //        this.agileRichTextBox_history.AppendRichText(showText, null, null, Color.DarkGray);
        //        this.agileRichTextBox_history.ScrollToCaret();
        //    }
        //}
        #endregion

        #region 显示文件传输失败的消息
        //internal void ShowFileTransferFailed(string projectName)
        //{
        //    if (this.InvokeRequired)
        //    {
        //        this.Invoke(new CbGeneric<string>(this.ShowFileTransferFailed), projectName);
        //    }
        //    else
        //    {
        //        DateTime showTime = DateTime.Now;
        //        this.agileRichTextBox_history.AppendRichText(string.Format("{0}  {1}\n", "系统", showTime), null, null, Color.DarkGray);
        //        string showText = string.Format("文件{0}下载失败！\n ", projectName);
        //        this.agileRichTextBox_history.AppendRichText(showText, null, null, Color.DarkGray);
        //        this.agileRichTextBox_history.ScrollToCaret();
        //    }
        //}
        #endregion

        #region 截屏
                
        private void toolStripButton_cut_Click(object sender, EventArgs e)
        {
            try
            {
                CaptureScreenForm form = new CaptureScreenForm();

                if (DialogResult.Cancel == form.ShowDialog())
                {
                    return;
                }
                if (form.CaptureRegion.Width == 0 && form.CaptureRegion.Height == 0)
                {
                    return;
                }
                Bitmap bitmap = ESBasic.Helpers.ScreenHelper.CaptureScreen(form.CaptureRegion);               
                //this.chatBox_send.InsertImage(bitmap);               
            }
            catch (Exception ee)
            {
                Program.Logger.Log(ee, "TextChatControl.toolStripButton_cut_Click", ESBasic.Loggers.ErrorLevel.High);
                MessageBox.Show(ee.Message);
            }

        } 
        #endregion

        private void toolStripButton1_MouseEnter(object sender, EventArgs e)
        {
            this.Focus();
        }

        private void toolStripButton1_MouseUp(object sender, MouseEventArgs e)
        {
            this.SetEmotionFormLocation();
            this.emotionForm.Visible = !this.emotionForm.Visible;
        }

        /// <summary>
        /// 追加系统时间
        /// </summary> 
        private void AppendSendTime(DateTime time)
        {
            lock (this.locker)
            {
                if (time.Subtract(this.lastMessageTime) > TimeSpan.FromMinutes(5))
                {
                    this.lastMessageTime = time;
                    this.chatRender.AddChatItemTime(time);
                }
            }
        }
    }   
}
