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

namespace ISIM
{
    public partial class ChatForm : Form
    {
        private FormWindowState lastState;
        private bool IsFormClosing = false;

        public ChatForm(ISIMContact contact)
        {
            InitializeComponent();

            lastState = WindowState;
            this.TopMost = Global.OpenForms.mainForm.TopMost;
            chatTabs.AddTab(contact, true);
            chatTabs.ChatTabs_Resize(null, null);
            this.Text = Global.Converter.GetRenamedContactName(contact);
        }

        /// <summary>
        /// Čekování stisknutých kláves, změna aktivního tabu
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.Shift | Keys.Tab))
            {
                if (chatTabs.SelectedIndex > 0)
                    chatTabs.SelectedIndex--;
                else
                    chatTabs.SelectedIndex = chatTabs.TabPages.Count - 1;
                return true;
            }
            else if (keyData == (Keys.Control | Keys.Tab))
            {
                foreach (ChatTabPage page in chatTabs.TabPages)
                {
                    if ((page.contact != null) && (page.contact.unreadedMessage == true))
                    {
                        chatTabs.SelectedTab = page;
                        return true;
                    }
                }

                if (chatTabs.SelectedIndex < chatTabs.TabPages.Count - 1)
                    chatTabs.SelectedIndex++;
                else
                    chatTabs.SelectedIndex = 0;
                return true;
            }

            if ((keyData == Keys.Escape) || (keyData == (Keys.Control | Keys.W)))
                CloseTab(chatTabs.SelectedTab as ChatTabPage);

            return base.ProcessCmdKey(ref msg, keyData);
        }

        public bool CloseTab(ChatTabPage tabPage)
        {
            if (tabPage.contact.unreadedMessage)
            {
                if (MessageBox.Show(Global.LangManager.Translate("unreadedMessage") + " " + Global.LangManager.Translate("from") + " " + Global.Converter.GetRenamedContactName(tabPage.contact) + ".\n" + Global.LangManager.Translate("close") + "?", Global.LangManager.Translate("unreadedMessage"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }
                else
                    tabPage.contact.unreadedMessage = false;
            }

            if (tabPage.msgTb.TextLength > 0)
            {
                if (MessageBox.Show(Global.LangManager.Translate("unfinishedMessage") + " " + Global.LangManager.Translate("forPrep") + " " + Global.Converter.GetRenamedContactName(tabPage.contact) + ".\n" + Global.LangManager.Translate("close") + "?", Global.LangManager.Translate("unfinishedMessage"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }
                else
                    tabPage.msgTb.Clear();
            }

            chatTabs.RemoveTab(tabPage);
            GC.Collect();

            if (chatTabs.TabCount == 0)
                this.Close();

            return true;
        }

        private void ChatForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Global.OpenForms.chatForm = null;
        }

        private void chatTabs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chatTabs.SelectedTab == null)
                return;
            
            if (((chatTabs.SelectedTab as ChatTabPage).contact.unreadedMessage) && (!IsFormClosing))
            {
                (chatTabs.SelectedTab as ChatTabPage).contact.unreadedMessage = false;

                Global.OpenForms.mainForm.Invoke(new MethodInvoker(() => { Global.OpenForms.mainForm.Refresh(); }));
                chatTabs.Refresh();
            }

            chatTabs.ChatTabs_Resize(null, null);
            (chatTabs.SelectedTab as ChatTabPage).msgTb.Focus();

            this.Text = Global.Converter.GetRenamedContactName((chatTabs.SelectedTab as ChatTabPage).contact);
        }

        private void ChatForm_Shown(object sender, EventArgs e)
        {
            (chatTabs.SelectedTab as ChatTabPage).msgTb.Focus();
        }

        private void ChatForm_Load(object sender, EventArgs e)
        {
            try
            {
                if (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormWidth"))
                    this.Width = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormWidth"]);
                if (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormHeight"))
                    this.Height = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormHeight"]);

                if ((Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormPosX")) && (Global.settingsDictionary["ISIMsettings"].ContainsKey("chatFormPosY")))
                {
                    int x = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormPosX"]);
                    int y = int.Parse(Global.settingsDictionary["ISIMsettings"]["chatFormPosY"]);
                    // ošetření vyskočení okna mimo obrazovku
                    if ((x >= Screen.PrimaryScreen.WorkingArea.Width - 5) || (x < 0 - this.Width + 5)) x = Screen.PrimaryScreen.WorkingArea.Width / 2;
                    if ((y >= Screen.PrimaryScreen.WorkingArea.Height - 5) || (y < 0 - this.Height + 5)) y = Screen.PrimaryScreen.WorkingArea.Height / 2;

                    this.Location = new Point(x, y);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("cannot set chatform properties");
            }
        }

        private void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsFormClosing = true;
            foreach (ChatTabPage tab in chatTabs.TabPages)
            {
                if (!CloseTab(tab))
                {
                    e.Cancel = true;
                    IsFormClosing = false;
                    chatTabs_SelectedIndexChanged(null, null);
                    return;
                }
            }

            Global.ChangeISIMsettings("chatFormWidth", this.Width.ToString());
            Global.ChangeISIMsettings("chatFormHeight", this.Height.ToString());

            Global.ChangeISIMsettings("chatFormPosX", this.Location.X.ToString());
            Global.ChangeISIMsettings("chatFormPosY", this.Location.Y.ToString());
        }

        private void chatTabs_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Middle)
            {
                Point p = chatTabs.PointToClient(Cursor.Position);
                for (int i = 0; i < chatTabs.TabCount; i++)
                {
                    Rectangle r = chatTabs.GetTabRect(i);
                    if (r.Contains(p))
                    {
                        CloseTab(chatTabs.TabPages[i] as ChatTabPage);
                        break;
                    }
                }
            }
        }

        private int clickedTabIndex = -1;
        private void tabMenu_Opening(object sender, CancelEventArgs e)
        {
            elisToolStripMenuItem.Visible = Global.elisActivated;

            openProfile.Text = Global.LangManager.Translate("openProfile");
            chatHistory.Text = Global.LangManager.Translate("history");
            closeTab.Text = Global.LangManager.Translate("close");

            Point p = this.chatTabs.PointToClient(Cursor.Position);
            for (int i = 0; i < this.chatTabs.TabCount; i++)
            {
                Rectangle r = this.chatTabs.GetTabRect(i);
                if (r.Contains(p))
                {
                    clickedTabIndex = i;

                    ISIMContact contact = (chatTabs.TabPages[i] as ChatTabPage).contact;

                    chatHistory.Visible = File.Exists(Global.appDataFolder + "conversations" + Path.DirectorySeparatorChar + TextEdit.RemoveInvalidCharactersFromFileName(chatTabs.TabPages[i].Name) + ".txt");

                    openProfile.Visible = contact.protocol == "facebook";

                    elisToolStripMenuItem.Checked = contact.elisActive;

                    return;
                }
            }
            clickedTabIndex = -1;
            e.Cancel = true;
        }

        private void closeTab_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
                CloseTab(chatTabs.TabPages[clickedTabIndex] as ChatTabPage);
        }

        private void chatHistory_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            {
                string args = string.Format("/Select, {0}", Global.appDataFolder + "conversations" + Path.DirectorySeparatorChar + TextEdit.RemoveInvalidCharactersFromFileName(chatTabs.TabPages[clickedTabIndex].Name) + ".txt");

                System.Diagnostics.ProcessStartInfo pfi = new System.Diagnostics.ProcessStartInfo("explorer.exe", args);
                System.Diagnostics.Process.Start(pfi);
            }
        }

       
        private void openProfile_Click(object sender, EventArgs e)
        {
            if (clickedTabIndex != -1)
            { 
                ISIMContact contact = (chatTabs.TabPages[clickedTabIndex] as ChatTabPage).contact;
                if (contact.protocol == "facebook")
                {
                    string fbId = contact.id.Replace("@chat.facebook.com", "");
                    if (fbId.Substring(0, 1) == "-") fbId = fbId.Substring(1);
                    System.Diagnostics.Process.Start("http://www.facebook.com/" + fbId);
                }
            }
        }

       
        private void ChatForm_Resize(object sender, EventArgs e)
        {
            if (lastState != WindowState)
            {
                lastState = WindowState;
                if (WindowState != FormWindowState.Minimized)
                    chatTabs_SelectedIndexChanged(null, null);
            }
        }

        private void elisToolStripMenuItem_Click(object sender, EventArgs e)
        {
            elisToolStripMenuItem.Checked = !elisToolStripMenuItem.Checked;
            (chatTabs.SelectedTab as ChatTabPage).contact.elisActive = elisToolStripMenuItem.Checked;
        }

    }
}
