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

namespace OsaGateway
{
    public partial class Main : Form
    {

        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();

        private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        public delegate void BlinkDelegate();

        public Main()
        {
            InitializeComponent();
            Message.MessageAdded += new Message.MessageHandler(RefreshList);
            Message.MessageDeleted += new Message.MessageHandler(RefreshList);
            Calls.CallAdded += new Calls.CallDelegate(RefreshList);
            Calls.CallDeleted += new Calls.CallDelegate(RefreshList);
            Program.gateway.IncommingMessage += new GatewayCommon.GatewayControl.IncommingMessageHandler(gateway_IncommingMessage);
            Program.gateway.IncommingCall += new GatewayCommon.GatewayControl.IncommingCallHandler(gateway_IncommingCall);
            CallDetail.NewCallChange += new CallDetail.CallDetailHandler(RefreshList);
            SMSDetail.NewSMSChange += new SMSDetail.SMSDetailHandler(RefreshList);
            Contact.ContactAdded += new Contact.ContactHandler(RefreshList);
            Contact.ContactRemoved += new Contact.ContactHandler(RefreshList);
            Contact.ContactUpdated += new Contact.ContactHandler(RefreshList);
        }
        ~Main()
        {
            Program.gateway.Close();
        }

        public void ShowNewSMS()
        {
            //pbSMS.Visible = true;
            panel1.BackColor = Color.OrangeRed;
        }
        public void HideNewSMS()
        {
            //pbSMS.Visible = false;
            panel1.BackColor = Color.DimGray;
        }
        public void ShowNewCall()
        {
            //pbCall.Visible = true;
            panel2.BackColor = Color.OrangeRed;
        }
        public void HideNewCall()
        {
            //pbCall.Visible = false;
            panel2.BackColor = Color.DimGray;
        }

        private void gateway_IncommingMessage(string phoneNumber, string message, DateTime incommingDate)
        {
            Message newMessage = new Message();
            newMessage.Date = incommingDate;
            newMessage.GUID = Guid.NewGuid();
            newMessage.Phone = phoneNumber;
            newMessage.Text = message;
            newMessage.TrafficType = TrafficType.Incomming;
            Program.NewSMSGuid.Add(newMessage.GUID.ToString());
            newMessage.Add(newMessage);

            if (this.InvokeRequired)
                this.EndInvoke(this.BeginInvoke(new BlinkDelegate(RefreshList)));
            else
                RefreshList();
        }
        private void gateway_IncommingCall(string phoneNumber, DateTime incommingDate)
        {
            Calls newCall = new Calls();
            newCall.Date = incommingDate;
            newCall.GUID = Guid.NewGuid();
            newCall.Phone = phoneNumber;
            newCall.TrafficType = TrafficType.Incomming;
            Program.NewCallGuid.Add(newCall.GUID.ToString());
            newCall.Add(newCall);

            if (this.InvokeRequired)
                this.EndInvoke(this.BeginInvoke(new BlinkDelegate(RefreshList)));
            else
                RefreshList();
        }

        public void RefreshList()
        {
            if (Program.NewSMSGuid.Count > 0)
            {
                if (this.InvokeRequired)
                    this.EndInvoke(this.BeginInvoke(new BlinkDelegate(ShowNewSMS)));
                else
                    ShowNewSMS();
            }
            else
            {
                if (this.InvokeRequired)
                    this.EndInvoke(this.BeginInvoke(new BlinkDelegate(HideNewSMS)));
                else
                    HideNewSMS();
            }
            if (Program.NewCallGuid.Count > 0)
            {
                if (this.InvokeRequired)
                    this.EndInvoke(this.BeginInvoke(new BlinkDelegate(ShowNewCall)));
                else
                    ShowNewCall();
            }
            else
            {
                if (this.InvokeRequired)
                    this.EndInvoke(this.BeginInvoke(new BlinkDelegate(HideNewCall)));
                else
                    HideNewCall();
            }

            if (CheckListOpening() != 0)
            {
                if (CheckListOpening() == 1)
                {
                    dgMain.DataSource = Message.GetAll(TrafficType.Incomming);
                }
                if (CheckListOpening() == 2)
                {
                    dgMain.DataSource = Message.GetAll(TrafficType.Outgoing);
                }
                if (CheckListOpening() == 3)
                {
                    dgMain.DataSource = Calls.GetAll(TrafficType.Incomming);
                }
                if (CheckListOpening() == 4)
                {
                    dgMain.DataSource = Calls.GetAll(TrafficType.Outgoing);
                }
                dgMain.ClearSelection();
            }
        }
        private void ClearButtonStyle()
        {
            button1.BackColor = Color.Black;
            button2.BackColor = Color.Black;
            button3.BackColor = Color.Black;
            button4.BackColor = Color.Black;
            button1.ForeColor = Color.White;
            button2.ForeColor = Color.White;
            button3.ForeColor = Color.White;
            button4.ForeColor = Color.White;
        }
        private int CheckListOpening()
        {
            if (button1.BackColor == Color.OrangeRed)
                return 1;
            if (button2.BackColor == Color.OrangeRed)
                return 2;
            if (button4.BackColor == Color.OrangeRed)
                return 3;
            if (button3.BackColor == Color.OrangeRed)
                return 4;
            return 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (CheckListOpening() != 1)
            {
                if (CheckListOpening() == 0)
                {
                    this.Size = new Size(this.Size.Width, this.Size.Height + 300);
                }
                ClearButtonStyle();
                button1.BackColor = Color.OrangeRed;
                button1.ForeColor = Color.Black;

                dgMain.Columns["cGuid"].DataPropertyName = "GUID";
                dgMain.Columns["cDate"].DataPropertyName = "Date";
                dgMain.Columns["cFrom"].DataPropertyName = "Phone";
                dgMain.Columns["cTraffic"].DataPropertyName = "TrafficType";
                dgMain.Columns["cMessage"].DataPropertyName = "Text";

                RefreshList();
            }
            else
            {
                this.Size = new Size(this.Size.Width, this.Size.Height - 300); ;
                ClearButtonStyle();
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (CheckListOpening() != 2)
            {
                if (CheckListOpening() == 0)
                {
                    this.Size = new Size(this.Size.Width, this.Size.Height + 300);
                }
                ClearButtonStyle();
                button2.BackColor = Color.OrangeRed;
                button2.ForeColor = Color.Black;

                dgMain.Columns["cGuid"].DataPropertyName = "GUID";
                dgMain.Columns["cDate"].DataPropertyName = "Date";
                dgMain.Columns["cFrom"].DataPropertyName = "Phone";
                dgMain.Columns["cTraffic"].DataPropertyName = "TrafficType";
                dgMain.Columns["cMessage"].DataPropertyName = "Text";

                RefreshList();
            }
            else
            {
                this.Size = new Size(this.Size.Width, this.Size.Height - 300); ;
                ClearButtonStyle();
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (CheckListOpening() != 3)
            {
                if (CheckListOpening() == 0)
                {
                    this.Size = new Size(this.Size.Width, this.Size.Height + 300);
                }
                ClearButtonStyle();
                button4.BackColor = Color.OrangeRed;
                button4.ForeColor = Color.Black;

                dgMain.Columns["cGuid"].DataPropertyName = "GUID";
                dgMain.Columns["cDate"].DataPropertyName = "Date";
                dgMain.Columns["cFrom"].DataPropertyName = "Phone";
                dgMain.Columns["cTraffic"].DataPropertyName = "TrafficType";
                dgMain.Columns["cMessage"].DataPropertyName = null;

                RefreshList();
            }
            else
            {
                this.Size = new Size(this.Size.Width, this.Size.Height - 300);
                ClearButtonStyle();
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (CheckListOpening() != 4)
            {
                if (CheckListOpening() == 0)
                {
                    this.Size = new Size(this.Size.Width, this.Size.Height + 300);
                }
                ClearButtonStyle();
                button3.BackColor = Color.OrangeRed;
                button3.ForeColor = Color.Black;

                dgMain.Columns["cGuid"].DataPropertyName = "GUID";
                dgMain.Columns["cDate"].DataPropertyName = "Date";
                dgMain.Columns["cFrom"].DataPropertyName = "Phone";
                dgMain.Columns["cTraffic"].DataPropertyName = "TrafficType";
                dgMain.Columns["cMessage"].DataPropertyName = null;

                RefreshList();
            }
            else
            {
                this.Size = new Size(this.Size.Width, this.Size.Height - 300);
                ClearButtonStyle();
            }
        }

        private void dgMain_DataSourceChanged(object sender, EventArgs e)
        {
            List<Contact> contacts = Contact.GetAll();
            for (int i = 0; i < dgMain.Rows.Count; i++)
            {
                if (contacts.Where(a => ("+420" + a.Phone).Contains(dgMain.Rows[i].Cells["cFrom"].Value.ToString())).Count() > 0)
                    dgMain.Rows[i].Cells["cFrom"].Value = contacts.Where(a => ("+420" + a.Phone).Contains(dgMain.Rows[i].Cells["cFrom"].Value.ToString())).FirstOrDefault().Name;


                string tmp = Program.NewSMSGuid.Where(a => a == dgMain.Rows[i].Cells["cGuid"].Value.ToString()).FirstOrDefault();
                string tmp2 = Program.NewCallGuid.Where(a => a == dgMain.Rows[i].Cells["cGuid"].Value.ToString()).FirstOrDefault();
                if ((tmp != null && tmp.Count() > 0) || (tmp2 != null && tmp2.Count() > 0))
                {
                    dgMain.Rows[i].DefaultCellStyle.BackColor = Color.OrangeRed;
                }
                else
                {
                    dgMain.Rows[i].DefaultCellStyle.BackColor = Color.Gray;
                }
            }
        }
        private void dgMain_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (CheckListOpening() == 1 || CheckListOpening() == 2)
            {
                SMSDetail smsDetail = new SMSDetail(new Guid(dgMain.Rows[e.RowIndex].Cells["cGuid"].Value.ToString()));
                smsDetail.Show();
            }
            if (CheckListOpening() == 3 || CheckListOpening() == 4)
            {
                CallDetail callDetail = new CallDetail(new Guid(dgMain.Rows[e.RowIndex].Cells["cGuid"].Value.ToString()));
                callDetail.Show();
            }
        }
        private void dgMain_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (CheckListOpening() == 1)
            {
                string[] tmp = Program.NewSMSGuid.ToArray();
                if (tmp != null && tmp.Count() > 0)
                {
                    foreach (string item in tmp)
                    {
                        if (item == dgMain.Rows[e.RowIndex].Cells["cGuid"].Value.ToString())
                        {
                            Program.NewSMSGuid.Remove(item);
                        }
                    }
                    dgMain.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gray;
                    if (tmp.Count() == 1)
                        HideNewSMS();
                }
            }
            if (CheckListOpening() == 3)
            {
                string[] tmp = Program.NewCallGuid.ToArray();
                if (tmp != null && tmp.Count() > 0)
                {
                    foreach (string item in tmp)
                    {
                        if (item == dgMain.Rows[e.RowIndex].Cells["cGuid"].Value.ToString())
                        {
                            Program.NewCallGuid.Remove(item);
                        }
                    }
                    dgMain.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Gray;
                    if (tmp.Count() == 1)
                        HideNewCall();
                }
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            NewSMS newSMS = new NewSMS();
            newSMS.Show();
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            NewCall nc = new NewCall();
            nc.Show();
        }
        private void pictureBox3_Click(object sender, EventArgs e)
        {
            Contacts contacts = new Contacts();
            contacts.Show();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (dgMain.SelectedRows.Count > 0)
            {
                Contact contact = Contact.GetByName(dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString());
                if (contact != null)
                {
                    toolStripMenuItem1.Enabled = false;
                    toolStripMenuItem2.Enabled = true;
                    toolStripMenuItem3.Enabled = true;
                }
                else
                {
                    toolStripMenuItem1.Visible = true;
                    toolStripMenuItem2.Enabled = true;
                    toolStripMenuItem3.Enabled = true;
                }
            }
            else
            {
                toolStripMenuItem1.Enabled = false;
                toolStripMenuItem2.Enabled = false;
                toolStripMenuItem3.Enabled = false;
            }
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            NewContact nc = new NewContact(new Contact(string.Empty, dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString()));
            nc.Show();
        }
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            string phoneNumbers = string.Empty;
            long tmpPhone;
            if (long.TryParse(dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString(), out tmpPhone))
                phoneNumbers += dgMain.SelectedRows[0].Cells["From"].Value.ToString() + "; ";
            else
                phoneNumbers += Contact.GetByName(dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString()).Phone;
            NewCall nc = new NewCall(phoneNumbers);
            nc.Show();
        }
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            string phoneNumbers = string.Empty;
            long tmpPhone;
            if (long.TryParse(dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString(), out tmpPhone))
                phoneNumbers += dgMain.SelectedRows[0].Cells["From"].Value.ToString() + "; ";
            else
                phoneNumbers += Contact.GetByName(dgMain.SelectedRows[0].Cells["cFrom"].Value.ToString()).Phone;
            NewSMS ns = new NewSMS(phoneNumbers);
            ns.Show();
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.Close();
        }
        private void pictureBox5_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
    }
}
