using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ISIM
{
    public partial class ChatTabPage : TabPage
    {
        public ConversationRTB convRtb = new ConversationRTB();
        public TextBox msgTb = new TextBox();
        public Button sendBtn = new Button();
        public ISIMContact contact;

        public ChatTabPage(ISIMContact contact)
        {
            InitializeComponent();

            
            this.Name = contact.id;
            this.Text = Global.Converter.GetRenamedContactName(contact).ReduceText(15);
            if (Text.Length < 7) Text += "   ";
            this.contact = contact;

            convRtb.Size = new Size(277, 210);
            convRtb.Location = new Point(0, 0);
            convRtb.ReadOnly = true;
            convRtb.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            convRtb.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
            convRtb.BackColor = Color.White;
            convRtb.Font = Global.chatFont;
            convRtb.KeyPress += convRtb_KeyPress;
            convRtb.LinkClicked += convRtb_LinkClicked;

            msgTb.Size = new Size(279, 54);
            msgTb.Location = new Point(0, 212);
            msgTb.Multiline = true;
            msgTb.KeyDown += msgTb_KeyDown;
            msgTb.KeyPress += msgTb_KeyPress;
            msgTb.TextChanged += msgTb_TextChanged;
            msgTb.Font = Global.chatFont;

            sendBtn.Image = Image.FromFile(Global.appRunPath + "graphics" + System.IO.Path.DirectorySeparatorChar + "sendMessageIcon.png");
            sendBtn.Size = new Size(56, 56);
            sendBtn.Location = new Point(279, 211);
            sendBtn.Click += sendBtn_Click;

            this.Controls.AddRange(new Control[] { convRtb, msgTb, sendBtn });

            string toolTip = Global.LangManager.Translate("name") + ": " + contact.name + "\n"
                            + "ID: " + contact.id + "\n"
                            + Global.LangManager.Translate("protocol") + ": " + contact.protocol + "\n";
            if (!String.IsNullOrEmpty(contact.client))
                toolTip += Global.LangManager.Translate("client") + ": " + contact.client;

            this.ToolTipText = toolTip;
        }

        void convRtb_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            Process.Start(e.LinkText);
        }

        void convRtb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (ModifierKeys != Keys.Control)
            {
                msgTb.AppendText(e.KeyChar.ToString());
                msgTb.Focus();
            }
        }

        int lastTextLength = 0;
        void msgTb_TextChanged(object sender, EventArgs e)
        {
            if (msgTb.TextLength > lastTextLength)
            {
                Global.ISIMFunctions.SendComposingNotification(contact);
                lastTextLength = msgTb.TextLength + 50;
            }

            if (msgTb.TextLength == 0)
                lastTextLength = 0;
        }

        void msgTb_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                e.Handled = true;
                return;
            }
        }

        void msgTb_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (e.Shift)
                {
                    int lastSelectionStart = msgTb.SelectionStart;
                    msgTb.Text = msgTb.Text.Insert(msgTb.SelectionStart, Environment.NewLine);
                    msgTb.SelectionStart = lastSelectionStart + Environment.NewLine.Length;
                    msgTb.ScrollToCaret();
                }
                else if (!e.Control)
                {
                    sendBtn_Click(null, null);
                }
                e.Handled = true;
            }
            else if ((e.Control) && (e.KeyCode == Keys.A))
            {
                msgTb.SelectAll();
                e.Handled = true;
            }
        }

        void sendBtn_Click(object sender, EventArgs e)
        {
            if ((contact.availability == Global.Availability.Blocked) || (Global.settingsDictionary["bannedList"].ContainsKey(contact.id)))
            {
                MessageBox.Show(Global.LangManager.Translate("contactIsBlockedUnblockFirst"));
                return;
            }

            if (msgTb.Text.Replace(" ", "").Length > 0)
            {
                Global.ISIMFunctions.SendChatMessage(contact, msgTb.Text);
                msgTb.Clear();
            }
            msgTb.Focus();
        }

        private string lastNick;
        private Dictionary<string, DateTime> lastMessage = new Dictionary<string, DateTime>();
        public void AddChatMessage(ISIMContact contact, string text, DateTime time, string from)
        {
            // uložím si, kdy jsem přijal poslední zprávu a pokud je další zpráva shodná a přijatá do 128 ms od poslední, nezpracovávám ji (občasné duplicity např. FB)
            if ((lastMessage.ContainsKey(text)) && (lastMessage[text] > DateTime.Now.AddMilliseconds(-128)))
                return;

            if (!msgTb.Focused)
                Global.ISIMFunctions.PlaySound(Global.ISIMFunctions.Sounds.incommingMessage);

            // přidání tagů pro barevné nicky
            // uzavře neuzavřené tagy
            string message = TextEdit.CloseTags(text);

            int nickColor = 0;
            if (from == Global.myNick)
                nickColor = 1;
            else if (from == Global.ISIM)
                nickColor = 2;
            else
            {
                nickColor = 3;
                from = Global.Converter.GetRenamedContactName(contact);
            }

            string msgPrefix = "";

            // aby se stále neopakoval prefix
            if (lastNick != from)
                msgPrefix = "\n" + "[color:" + nickColor + "]" + from + " (" + time.ToString("H:mm:ss  dd/MM/yyyy") + ")" + "[/color:" + nickColor + "]" + "\n";

            lastNick = from;

            lastMessage.Clear();
            lastMessage.Add(text, DateTime.Now);

            // pokud listuji v historii a kurzor je jinde, pak se nescrolluje
            int caretPos = 0;
            if (convRtb.Focused)
                caretPos = convRtb.SelectionStart;

            Global.ISIMFunctions.SaveConversation(contact.id, msgPrefix + message);

            convRtb.AppendText(msgPrefix + message + "\n");
            convRtb.Scroll(caretPos);
        }
    }
}
