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

namespace ISIM
{
    public partial class ConversationRTB : RichTextBox
    {
        private int lastAppendIndex = 0;

        public ConversationRTB()
        {
            InitializeComponent();
            this.Font = Global.chatFont;
        }
        

        /// <summary>
        /// Nahradí smajlíci obrázkama.
        /// </summary>
        public void EmoticonsAsImages()
        {
            int currentPosition;
            int currentPositionRtf;
            
            foreach (var smiley in TextEdit.EmoticonsList)
            {
                currentPosition = 0;
                currentPositionRtf = 0;
                while (this.Text.IndexOf(smiley.Key, currentPosition) != -1)
                {
                    try
                    {
                        currentPosition = this.Text.IndexOf(smiley.Key, currentPosition);
                        currentPositionRtf = this.Rtf.IndexOf(smiley.Key, currentPositionRtf);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        break;
                    }

                    if (currentPosition == -1) continue;

                    this.Rtf = this.Rtf.Insert(this.Rtf.IndexOf(smiley.Key, currentPositionRtf), smiley.Value);
                    this.Select(this.Text.IndexOf(smiley.Key, currentPosition), smiley.Key.Length);
                    this.SelectedText = "";
                }
            }
        }


        /// <summary>
        /// Smaže tagy [color:x] kde x je číslo od 1 do 3 a text mezi nimy obarvý a hodí ho tučně
        /// </summary>
        public void ColorText()
        {
            this.Select(lastAppendIndex, this.TextLength - lastAppendIndex);
            this.SelectionFont = Global.chatFont;

            int currentPosition;
            for (int i = 1; i <= 3; i++)
            {
                currentPosition = 0;
                while (this.Text.IndexOf("[color:" + i + "]", currentPosition) != -1)
                {
                    try
                    {
                        currentPosition = this.Text.IndexOf("[color:" + i + "]", currentPosition);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        break;
                    }

                    if ((this.Text.IndexOf("[/color:" + i + "]", currentPosition) - (currentPosition)) < 0) break;


                    this.SelectionStart = currentPosition + "[color:x]".Length;
                    this.SelectionLength = this.Text.IndexOf("[/color:" + i + "]", currentPosition) - currentPosition;

                    this.SelectionFont = new Font(this.Font.FontFamily, this.Font.Size, FontStyle.Bold);
                    switch (i)
                    {
                        case 1:
                            this.SelectionColor = Color.Blue;
                            break;

                        case 2:
                            this.SelectionColor = Color.Green;
                            break;

                        case 3:
                            this.SelectionColor = Color.Red;
                            break;
                    }

                    this.Select(this.Text.IndexOf("[color:" + i + "]", currentPosition), "[color:x]".Length);
                    this.SelectedText = "";

                    this.Select(this.Text.IndexOf("[/color:" + i + "]", currentPosition), "[/color:x]".Length);
                    this.SelectedText = "";
                }
            }
        }

        new public void AppendText(string text)
        {
            this.ReadOnly = false;

            lastAppendIndex = this.TextLength;
            base.AppendText(text);

            ColorText();

            if ((!Global.settingsDictionary["ISIMsettings"].ContainsKey("enableEmoticons")) || (bool.Parse(Global.settingsDictionary["ISIMsettings"]["enableEmoticons"])))
                EmoticonsAsImages();


            // Smazání několika prvních rádků, při velké délce. Aby nedošlo k přetečení velikosti RTB
            if ((this.Lines.Length > 128) || (this.Rtf.Length >= this.MaxLength))
            {
                this.SelectionStart = 0;
                this.SelectionLength = this.GetFirstCharIndexFromLine(16);
                this.SelectedText = "";
            }

            this.ReadOnly = true;
        }


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
        private const int WM_VSCROLL = 277;
        private const int SB_PAGEBOTTOM = 7;

        private void ScrollToBottom()
        {
            SendMessage(this.Handle, WM_VSCROLL, (IntPtr)SB_PAGEBOTTOM, IntPtr.Zero);
        }

        public void Scroll(int caretPos = 0)
        {
            if (this.Focused)
            {
                if (caretPos == 0)
                    caretPos = this.TextLength;
                this.SelectionStart = caretPos;
                this.ScrollToCaret();
            }
            else
                this.ScrollToBottom();
        }
    }
}
