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;

namespace The_Contacts
{
    public partial class NewContact : Form
    {
        public NewContact(string Userid)
        {
            InitializeComponent();
            UserID = Userid;
        }
        string UserID;

        SqlConnection objSqlConnection;
        SqlCommand objSQLcommand;
        int No()
        {
            //Check if isn't any Contacts return1 یعنی اولین مخاطب در جدول
            objSQLcommand.CommandText = "Select No From Contact";
            SqlDataReader DR = objSQLcommand.ExecuteReader();
            DR.Read();
            bool blnHasRows = DR.HasRows;
            if (DR.IsClosed == false) DR.Close();
            if (!blnHasRows) return 1;
            //Get No from DataBase
            objSQLcommand.CommandText = "Select max (No) From Contact";
            return (int)objSQLcommand.ExecuteScalar() + 1;
            

        }
        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtNote.Clear();
        }
        String DataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pars Contacts\DataBase.mdf";
  

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog O = new OpenFileDialog();
            O.Title = "Select Text File";
            O.Filter= "TextFiles(*.txt)|*.txt|All Files(*.*)|*.*";
            O.Multiselect = false;
            if (O.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    txtNote.Text += System.IO.File.ReadAllText(O.FileName);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
           
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePicker1.Enabled = !chkforgetBirthday.Checked;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtname.Text = txtlastname.Text = txttel.Text = txtmob.Text = "";
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtweb.Text = txte.Text = "";
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtjob.Text = txtad1.Text = txtad2.Text = "";
        }



        private void vistaApiPicture1_Click(object sender, EventArgs e)
        {
            
        }
        bool blnBigsize=false;
        private void menuItem1_Click(object sender, EventArgs e)
        {
            OpenFileDialog O = new OpenFileDialog();
            O.Title = "Select an Image";
            O.Filter = "Images File|*.png;*.jpg;*.bmp;*.gif";
            O.Multiselect = false;
            if (O.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    vistaPictureBox1.Image = Image.FromFile(O.FileName);
                    Bitmap bmp = new Bitmap(O.FileName);
                    lblSize.Text = bmp.Height.ToString() + "×" + bmp.Width.ToString() ;
           
                    lblName.Text = new System.IO.FileInfo(O.FileName).Name;
                    System.IO.FileInfo File1 = new System.IO.FileInfo(O.FileName);
                    panel1.Show();
                    lblSizeOnDisk.Text = File1.Length / 1024 + " KB";
                    if ((File1.Length / 1024) > 400)
                    {
                        lblImageError.Text = "حجم فایل شما بیش تر از 400 کیلوبایت است این فایل قابل قبول نیست";
                        imgError.Show();
                        lblImageError.Show();
                        lblSizeOnDisk.ForeColor = Color.Red;
                        blnBigsize = true;
                        
                    }
                    else
                    {
                        imgError.Visible = lblImageError.Visible = false;
                        lblSizeOnDisk.ForeColor = Color.Green;
                        blnBigsize = false;
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            vistaPictureBox1.Image = Properties.Resources._1324041534_User_Black;
            panel1.Hide();
            lblImageError.Visible = imgError.Visible = false;
            blnBigsize = false;

        }
        Boolean isintoDataBase(string name, string family)
        {
            objSQLcommand.CommandText = "select Count(*) from Contact where name=N'" + name + "' and lastname=N'" + family + "'";
            int Value = (int)objSQLcommand.ExecuteScalar();
            if (Value > 0) return true;
            return false;
 
            
        }
        private void picTing1_Click(object sender, EventArgs e)
        {
            int i = No();
            if (txtname.Text.Trim() == "" || txtlastname.Text.Trim() == "")
            {
                MessageBox.Show("لطفا فیلد های نام و نام خانوادگی را پر کنید", "New", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (blnBigsize)
            {
                MessageBox.Show("حجم عکس بیشتر از 400 کیلوبایت قابل قبول نمی باشد", "New", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            if (isintoDataBase(txtname.Text, txtlastname.Text))
            {
                MessageBox.Show("مخاطبی با این نام قبلا به ثبت رسیده است", "New", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
           
            try
            {
                objSQLcommand = new SqlCommand("insert into contact (id,name,lastname,tel,mobile,web,email,job,address1,address2,note,image,ISfamily,no,birthday,star) values(@uId,@name,@lastname,@tel,@mob,@web,@email,@job,@ad1,@ad2,@note,@img,@isfamily,@no,@birthday,@star)", objSqlConnection);
                objSQLcommand.Parameters.AddWithValue("@uId", UserID);
                objSQLcommand.Parameters.AddWithValue("@name", txtname.Text);
                objSQLcommand.Parameters.AddWithValue("@lastname", txtlastname.Text);
                objSQLcommand.Parameters.AddWithValue("@tel", txttel.Text);

                objSQLcommand.Parameters.AddWithValue("@mob", txtmob.Text);
                objSQLcommand.Parameters.AddWithValue("@web", txtweb.Text);
                objSQLcommand.Parameters.AddWithValue("@email", txte.Text);
                objSQLcommand.Parameters.AddWithValue("@job", txtjob.Text);
                objSQLcommand.Parameters.AddWithValue("@ad1", txtad1.Text);
                objSQLcommand.Parameters.AddWithValue("@ad2", txtad2.Text);
                objSQLcommand.Parameters.AddWithValue("@note", txtNote.Text);
                objSQLcommand.Parameters.AddWithValue("@star", gradeProccesBar1.Value);
                objSQLcommand.Parameters.AddWithValue("@img", ConvertIMGtoByte(vistaPictureBox1.Image));
                objSQLcommand.Parameters.AddWithValue("@isfamily", ckhFamily.Checked.ToString());
                objSQLcommand.Parameters.AddWithValue("@no",i.ToString());
                if (chkforgetBirthday.Checked)
                {
                    objSQLcommand.Parameters.AddWithValue("@birthday", "False");
                }
                else
                {
                    objSQLcommand.Parameters.AddWithValue("@birthday", dateTimePicker1.Value.ToShortDateString());
                }
                objSQLcommand.ExecuteNonQuery();
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+"\nPlease try again", "error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            
          
           
  
                
            
            
        }
        byte[] ConvertIMGtoByte(Image image)
        {
            Bitmap b = new Bitmap(image);
            System.IO.MemoryStream M = new System.IO.MemoryStream();
            b.Save(M, System.Drawing.Imaging.ImageFormat.Png);
            return M.ToArray();

        }

        private void NewContact_Load(object sender, EventArgs e)
        {
            objSQLcommand = new SqlCommand();
            objSqlConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + DataDirectory + ";Integrated Security=True;User Instance=True");
            objSQLcommand.Connection = objSqlConnection;
            objSqlConnection.Open();
            chkforgetBirthday.Checked = true;
            panel1.Hide();
          
  
        }

        private void vistaPictureBox1_Click(object sender, EventArgs e)
        {
            contextMenu1.Show(vistaPictureBox1, ShowIIB);
        }

        private void vistaPictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            ShowIIB = new Point(e.X, e.Y);
        }
        Point ShowIIB;

        private void linkLabel1_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
        {
            vistaPictureBox1.Image = Properties.Resources._1324041534_User_Black;
            panel1.Hide();
            lblImageError.Visible = imgError.Visible = false;
            blnBigsize = false;
        }

        private void linkLabel6_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            menuItem1_Click(null, null);
        }
 

  
    }
}
