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.Data.SqlClient;
using System.Runtime.InteropServices;
using System.IO;

namespace The_Contacts
{
    public partial class MainForm : Form
    {
        public MainForm(string ID)
        {
            InitializeComponent();
            UserId = ID;
            ContextMenu = contextMenu1;
            listView1.ContextMenu = contextMenu1;
        }
        #region Publish
        string UserId;
        SqlConnection objSqlConnection;
        SqlCommand objSQLcommand;
        String DataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pars Contacts\DataBase.mdf";
        string FavouritePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pars Contacts\Favourite.txt";
        void AddFavouriteIconToImage(Image image)
        {
            Graphics G = Graphics.FromImage(image);
            G.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            G.DrawImage(Properties.Resources.Favourite, new Point(0, 0));
            G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        }
        void CheckFavouritePathExits()
        {
            if (File.Exists(FavouritePath) == false)
            {
                File.Create(FavouritePath);
            }
        }
        bool IsNewContact()
        {
            if (listView1.Items[0].Text.ToLower() == "مخاطب جدید" && listView1.Items[0].SubItems[1].Text.ToLower() == "برای شروع اینجا را کلیک کنید") return true;
            else
                return false;
        }
        bool blnLogOut = false;
        void LogOut()
        {
            blnLogOut = true;
            this.Close();
        }
        bool CheckFavourite(string no, string FullName)
        {
            CheckFavouritePathExits();
            string[] Favs = File.ReadAllLines(FavouritePath);
            foreach (string str in Favs)
            {
                if (str == no + "  :" + FullName) return true;
            }
            return false;
        }
        Image IMGFROMBYTE(byte[] bytes)
        {
            System.IO.MemoryStream M = new System.IO.MemoryStream(bytes);
            return Image.FromStream(M);
        }       
        void FavouirteAndFamilyMenuItemClick(object sender, EventArgs e)
        {
            String No = ((MenuItem)sender).Tag.ToString();
            View V = new View(No);
            V.ShowDialog();
           
            
        }
        int TotalFavouirtes=0, TotalFamily = 0;
        #endregion
        #region Load and Close Form
        private void MainForm_Load(object sender, EventArgs e)
        {

            //Function to Total 
            TotalFamily = TotalFavouirtes = 0;
            List<string> LstBirthDaysName = new List<string>();
            try
            {
                //Show loading Picture
                PicLoading.Show();
                PicLoading.Show();

                //Data tools
                objSqlConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + DataDirectory + ";Integrated Security=True;User Instance=True");
                objSqlConnection.Open();
                objSQLcommand = new SqlCommand();
                objSQLcommand.Connection = objSqlConnection;

                //Try to Get Contacts
                SqlDataAdapter Da = new SqlDataAdapter("Select name,lastname,tel,mobile,email,image,isfamily,BirthDay,no,star from Contact where id=" + UserId, objSqlConnection);
                DataTable DT = new DataTable();
                Da.Fill(DT);
                listView1.Items.Clear();
                imageList1.Images.Clear();

                //Clear Favourite and Family Menu Items on Context menu Strip
                contextMenu3.MenuItems.Clear();
                contextMenu4.MenuItems.Clear();

                // foreach to Rows
                foreach (DataRow objDataRow in DT.Rows)
                {
                    //Get Contact Image
                    Image img = IMGFROMBYTE((byte[])objDataRow[5]);
                    //Check Favourites
                    if (CheckFavourite(objDataRow[8].ToString(), objDataRow[0] + " " + objDataRow[1]))
                    {
                        //Add an Icons to Contact Image
                        AddFavouriteIconToImage(img);

                        //add Favourite Function
                        TotalFavouirtes += 1;
                        MenuItem M = new MenuItem(objDataRow[0].ToString() + " " + objDataRow[1].ToString(), new EventHandler(FavouirteAndFamilyMenuItemClick));
                        M.Tag = objDataRow[8].ToString();
                        contextMenu3.MenuItems.Add(M);
                    }
                    //Check BirthDay

                    if (objDataRow[7].ToString().ToLower() != "false")
                    {
                        int Mounth, Day;
                        DateTime BirthDate = DateTime.Parse(objDataRow[7].ToString());
                        Mounth = BirthDate.Month;
                        Day = BirthDate.Day;
                        if (DateTime.Now.Month == Mounth && DateTime.Now.Day == Day)
                        {
                            LstBirthDaysName.Add(objDataRow[0].ToString() + " " + objDataRow[1].ToString());
              
      
                        }
                    }
                    //**************************************************
                    //Add to ListView

                    imageList1.Images.Add(img);
                    ListViewItem Lst = new ListViewItem(objDataRow[0] + " " + objDataRow[1], imageList1.Images.Count - 1, listView1.Groups["All"]);
                    if (objDataRow[2].ToString().Trim() != "")
                        Lst.SubItems.Add("تلفن:" + objDataRow[2].ToString());
                    else
                        Lst.SubItems.Add(" ");


                    if (objDataRow[3].ToString().Trim() != "")
                        Lst.SubItems.Add("موبایل:" + objDataRow[3].ToString());
                    else
                        Lst.SubItems.Add(" ");

                    if (objDataRow[4].ToString().Trim() != "")
                        Lst.SubItems.Add(objDataRow[4].ToString());
                    else
                        Lst.SubItems.Add(" ");
       
                    Lst.SubItems.Add(objDataRow[8].ToString());
                    Lst.SubItems.Add(objDataRow[9].ToString());
                    listView1.Items.Add(Lst);
                    //Check For Relative (Is Family)
                    if (objDataRow[6].ToString() == "True")
                    {
                        TotalFamily += 1;
                        //Now Add to Family Group
                        Image img2 = IMGFROMBYTE((byte[])objDataRow[5]);
                        MenuItem M = new MenuItem(objDataRow[0].ToString() + " " + objDataRow[1].ToString(), new EventHandler(FavouirteAndFamilyMenuItemClick));
                        M.Tag = objDataRow[8].ToString();
                        contextMenu4.MenuItems.Add(M);
                        if (CheckFavourite(objDataRow[8].ToString(), objDataRow[0] + " " + objDataRow[1]))
                        {
                            AddFavouriteIconToImage(img2);
                        }
                        imageList1.Images.Add(img2);
                        ListViewItem Lst2 = new ListViewItem(objDataRow[0] + " " + objDataRow[1], imageList1.Images.Count - 1, listView1.Groups["Family"]);
                        if (objDataRow[2].ToString().Trim() != "")
                            Lst2.SubItems.Add("تلفن:" + objDataRow[2].ToString());
                        else
                            Lst2.SubItems.Add("");

                        if (objDataRow[3].ToString().Trim() != "")
                            Lst2.SubItems.Add("موبایل:" + objDataRow[3].ToString());
                        else
                            Lst2.SubItems.Add("");

                        if (objDataRow[4].ToString().Trim() != "")
                            Lst2.SubItems.Add(objDataRow[4].ToString());
                        else
                            Lst2.SubItems.Add(" ");

                        Lst2.SubItems.Add(objDataRow[8].ToString());
                        Lst2.SubItems.Add(objDataRow[9].ToString());
                        listView1.Items.Add(Lst2);
                    }

                }
                //Hide Loads Picture
                PicLoading.Hide();
                lblLoading.Hide();
                //****************************************

                //Get  Nick name(User Realy Name)
                objSQLcommand.CommandText = "select nickname from users where id=" + UserId;
                SqlDataReader DR = objSQLcommand.ExecuteReader();
                DR.Read();
                linkLabel1.Text = DR[0].ToString();
                //SQL DataReader will be Close
                if (!DR.IsClosed) DR.Close();
                //Add Welcome (New Contact)Icon to List View
                if (listView1.Items.Count == 0)
                {
                    imageList1.Images.Clear();
                    imageList1.Images.Add(Properties.Resources._1327076287_start_here_ubuntustudio);
                    ListViewItem LSt = new ListViewItem("مخاطب جدید", 0, listView1.Groups[3]);
                    LSt.SubItems.Add("برای شروع اینجا را کلیک کنید");
                    listView1.Items.Add(LSt);
                }
                //************************************
                //Show Brith Days

                //

            }
            catch (Exception ex)
            {
                if (MessageBox.Show("خطا در شروع به کار نرم افزار:\n" + ex.Message, "خطا", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                {
                    MainForm_Load(null, null);

                }
                else
                {
                    Application.Exit();
                }
            }
       
            //Set Group Titles;
            listView1.Groups[0].Header = "All (" + listView1.Groups[0].Items.Count + ")";
            listView1.Groups[1].Header = "Family (" + listView1.Groups[1].Items.Count + ")";
            
            if (TotalFavouirtes == 0) picFavourites.Enabled = false;
            else picFavourites.Enabled = true;

            if (TotalFamily == 0) picTing5.Enabled = false;
            else picTing5.Enabled = true;

            HidePanel();
            if (LstBirthDaysName.Count > 0)
            {
                ShowBrithDayPanels(LstBirthDaysName);
                LstBirthDaysName.Clear();

            }
            else
                BirthDayPanel.Hide();
   

     
    

            
           
            
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (blnLogOut)
            {
                
                Form1 frm = new Form1();
                frm.Show();
                
            }
            else
            {
                Application.Exit();
            }
        }
        #endregion
        #region PicTings Click
        private void picTing5_Click_2(object sender, EventArgs e)
        {
            contextMenu4.Show(picFavourites, new Point(0, 0));
        }
        private void picTing1_Click(object sender, EventArgs e)
        {
            new NewContact(UserId).ShowDialog();
            MainForm_Load(sender, e);
          
        }
        private void picTing5_Click_1(object sender, EventArgs e)
        {
            contextMenu3.Show(picFavourites, new Point(0, 0));

        }
        private void piccancelSerch_Click(object sender, EventArgs e)
        {
            MainForm_Load(null, null);
            piccancelSerch.Hide();
            PicSerch.Show();

        }
        private void picTing2_Click(object sender, EventArgs e)
        {
            if (IsNewContact()) { return; }
            if (listView1.FocusedItem == null)
            {
                MessageBox.Show("لطفا یک مخاطب برای ویرایش را انتخاب کنید", "Editing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }
            if (listView1.SelectedItems.Count > 1)
            {
                MessageBox.Show("امکان ویرایش چند کاربر همزمان وجد ندارد\nلطفا فقط یک مخاطب را انتخاب کنید", "Editing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }


            new Edit(listView1.FocusedItem.SubItems[4].Text.ToString()).ShowDialog();
            
            MainForm_Load(sender, e);


        }
        private void picTing5_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "") return;
            Searching();




        }

        private void picTing4_Click(object sender, EventArgs e)
        {
            MainForm_Load(sender, e);
        }
        private void picTing3_Click(object sender, EventArgs e)
        {
            if (IsNewContact()) { return; }
            if (listView1.FocusedItem == null)
            {
                MessageBox.Show("لطفا یک مخاطب برای حذف را انتخاب کنید", "Editing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }
            if (listView1.SelectedItems.Count > 1)
            {
                MessageBox.Show("امکان حذف چند کاربر همزمان وجد ندارد\nلطفا فقط یک مخاطب را انتخاب کنید", "Editing", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return;
            }
            new Delete(listView1.FocusedItem.SubItems[4].Text.ToString(), listView1.FocusedItem.Text.ToString()).ShowDialog();
            MainForm_Load(null, null);

        }
        #endregion
        #region List View
        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            if (IsNewContact()) { new NewContact(UserId).ShowDialog(); MainForm_Load(null, null); return; }
            if (listView1.FocusedItem == null) return;
            string No = listView1.FocusedItem.SubItems[4].Text.ToString();
            new View(No).ShowDialog();
            MainForm_Load(null, null);
        }
        private void listView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (IsNewContact()) { return; }
            if (e.KeyCode == Keys.Delete)
            {
                picTing3_Click(null, null);
            }
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (listView1.FocusedItem == null || IsNewContact() || listView1.SelectedItems.Count > 1)
            {

                HidePanel();
                return;
            }

            gradeProccesBar1.Value = int.Parse(listView1.FocusedItem.SubItems[5].Text.ToString());
            txtmob.Text = listView1.FocusedItem.SubItems[2].Text.ToString().Replace("موبایل:", "");
            txtTel.Text = listView1.FocusedItem.SubItems[1].Text.ToString().Replace("تلفن:", "");
            txtEmail.Text = listView1.FocusedItem.SubItems[3].Text.ToString().Replace("ایمیل:", "");
            lblName.Text = listView1.FocusedItem.Text;


            ShowPanel();


        }
        #endregion
        #region Searching TextBox
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "")
                piccancelSerch_Click(sender, e);
        }
        void Searching()
        {
            PicLoading.Show();
            lblLoading.Show();


            SqlDataAdapter Da = new SqlDataAdapter("Select name,lastname,tel,mobile,email,image,isfamily,BirthDay,no,star from Contact where name Like N'%" + textBox1.Text + "%' or lastname Like N'%" + textBox1.Text + "%' and id=" + UserId, objSqlConnection);
            DataTable DT = new DataTable();
            Da.Fill(DT);
            listView1.Items.Clear();
            imageList1.Images.Clear();
            foreach (DataRow objDataRow in DT.Rows)
            {
                Image img = IMGFROMBYTE((byte[])objDataRow[5]);
                //Check Favourites
                if (CheckFavourite(objDataRow[8].ToString(), objDataRow[0] + " " + objDataRow[1]))
                {
                    //Add an Icons to Contact Image
                    AddFavouriteIconToImage(img);

                }
                imageList1.Images.Add(img);
                ListViewItem Lst = new ListViewItem(objDataRow[0] + " " + objDataRow[1], imageList1.Images.Count - 1, listView1.Groups["Search"]);
                if (objDataRow[2].ToString().Trim() != "")
                    Lst.SubItems.Add("تلفن:" + objDataRow[2].ToString());
                else
                    Lst.SubItems.Add(" ");


                if (objDataRow[3].ToString().Trim() != "")
                    Lst.SubItems.Add("موبایل:" + objDataRow[3].ToString());
                else
                    Lst.SubItems.Add(" ");

                if (objDataRow[4].ToString().Trim() != "")
                    Lst.SubItems.Add(objDataRow[4].ToString());
                else
                    Lst.SubItems.Add(" ");

                Lst.SubItems.Add(objDataRow[8].ToString());
                Lst.SubItems.Add(objDataRow[9].ToString());
                listView1.Items.Add(Lst);
     

            }
            listView1.Groups[2].Header = "Searching (" + listView1.Groups[2].Items.Count + ")";
            PicLoading.Hide();
            lblLoading.Hide();
        }
        
 

   

   

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) Searching();
        }
        #endregion

        #region MenuItem and Context Menu




        private void menuItem2_Click(object sender, EventArgs e)
        {
            new NewContact(UserId).ShowDialog();
            MainForm_Load(null, null);
        }

        private void menuItem3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("برای ساختن کاربر جدید شما باید از این حساب خارج شوید ایا قبول می کنید؟ ", "The Contacts", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                LogOut();
                new Newuser().Show();
               
            }
        }
   

        private void menuItem8_Click(object sender, EventArgs e)
        {
            LogOut();
        }

        private void contextMenu1_Popup(object sender, EventArgs e)
        {
            if (listView1.FocusedItem == null||(IsNewContact()))
            {
                menuItem4.Enabled = menuItem5.Enabled = menuItem6.Enabled =menuItem13.Enabled=menuItem14.Enabled= false;
 
            }
            else
            {
                menuItem4.Enabled = menuItem5.Enabled = menuItem6.Enabled = menuItem13.Enabled = menuItem14.Enabled = true;
                if (CheckFavourite(listView1.FocusedItem.SubItems[4].Text.ToString(), listView1.FocusedItem.SubItems[0].Text.ToString()))
                {
                    menuItem13.Enabled = false; menuItem14.Enabled = true;
                }
                else
                {
                    menuItem13.Enabled = true; menuItem14.Enabled = false;
                }
            }

        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            
            new Delete(listView1.FocusedItem.SubItems[4].Text.ToString(), listView1.FocusedItem.Text.ToString()).ShowDialog();
            MainForm_Load(null, null);
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {

            new Edit(listView1.FocusedItem.SubItems[4].Text.ToString()).ShowDialog();
            MainForm_Load(sender, e);
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            new View(listView1.FocusedItem.SubItems[4].Text.ToString()).ShowDialog();
            MainForm_Load(sender, e);
        }
        private void menuItem9_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void menuItem11_Click(object sender, EventArgs e)
        {
            new ChangePassword(UserId).ShowDialog();
        }

        private void menuItem13_Click(object sender, EventArgs e)
        {
            CheckFavouritePathExits();
            File.AppendAllText(FavouritePath,Environment.NewLine+ listView1.FocusedItem.SubItems[4].Text.ToString() + "  :" + listView1.FocusedItem.SubItems[0].Text.ToString());
            MainForm_Load(null, null);
        }


 
        
        private void menuItem14_Click(object sender, EventArgs e)
        {
            CheckFavouritePathExits();
            string Fav = File.ReadAllText(FavouritePath);
            Fav = Fav.Replace(listView1.FocusedItem.SubItems[4].Text.ToString() + "  :" + listView1.FocusedItem.SubItems[0].Text.ToString(), "");
            File.WriteAllText(FavouritePath, Fav);
            MainForm_Load(null, null);
            
        }

        private void menuItem17_Click(object sender, EventArgs e)
        {
            menuItem8_Click(null, null);
        }

        private void menuItem18_Click(object sender, EventArgs e)
        {
            menuItem9_Click(null, null);
        }
        #endregion
        #region Panel

        void ShowPanel()
        {
            ContactPanel.Visible = true;
        }
        void HidePanel()
        {
            ContactPanel.Visible = false;
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            HidePanel();
        }
        #endregion
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            contextMenu2.Show(linkLabel1, new Point(0, 0));
        }
       

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                objSQLcommand.CommandText = "update Contact set tel=@1,mobile=@2,Email=@3,Star=@4 where no =" + listView1.FocusedItem.SubItems[4].Text.ToString();
                objSQLcommand.Parameters.AddWithValue("@1", txtTel.Text);
                objSQLcommand.Parameters.AddWithValue("@2", txtmob.Text);
                objSQLcommand.Parameters.AddWithValue("@3", txtEmail.Text);
                objSQLcommand.Parameters.AddWithValue("@4", gradeProccesBar1.Value.ToString());
                objSQLcommand.ExecuteNonQuery();
                MainForm_Load(null, null);
                
            }
            catch { }
        }
        

        private void label7_Click(object sender, EventArgs e)
        {
            BirthDayPanel.Hide();
        }
        void ShowBrithDayPanels(List<string> List)
        {
            lblBirthDay.Text = "امروز تولد ";
            foreach (string str in List)
            {
                lblBirthDay.Text += " " + str + ",";
            }
            lblBirthDay.Text += " است";
            BirthDayPanel.Show();
        }



    }
}
