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.IO;

namespace The_Contacts
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Form1.CheckForIllegalCrossThreadCalls = false;
            this.ContextMenu = contextMenu1;
        }
        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";
        private void Form1_Load(object sender, EventArgs e)
        {
            //Check for Start
            if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pars Contacts"))
            {
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pars Contacts");
            }
            if (!File.Exists(FavouritePath))
            {
                File.Create(FavouritePath);
            }
            if (System.IO.File.Exists(Properties.Settings.Default.ImageDir) && Properties.Settings.Default.ImageDir != "")
            {
                vistaPictureBox1.Image = Image.FromFile(Properties.Settings.Default.ImageDir);
            }
            if (!System.IO.File.Exists(DataDirectory))
            {
                if (MessageBox.Show("خطا در برقراری ارتباط با دیتا بیس\nسیستم نتوانست فایل دیتا بیس را پیدا کند لطفا از وجود ان در ادرس زیر اطمینان حاصل فرمائید:\n" +DataDirectory, "404 not found", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                {
                    Form1_Load(sender, e);
                }
                else
                {
                    this.Close();
                    Application.Exit();
                }
            }
            //***************************************Welcome
           
            backgroundWorker1.RunWorkerAsync();
            FarsiDate.FarsiDateTime F = new FarsiDate.FarsiDateTime();
            labelBack2.Text += F.Today;
            if (Properties.Settings.Default.UserName + Properties.Settings.Default.Password != "")
            {
                checkBox1.Checked = true;
                textBox1.Text = Properties.Settings.Default.UserName;
                textBox2.Text = Properties.Settings.Default.Password;
            }



        }
        private void menuItem6_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("ایا می خواهید نرم افزار را ترک کنید؟", "The Contacts", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                //Close Application
                Application.Exit();
            }
        }
        void RememberTools()
        {
            if (checkBox1.Checked)
            {
                Properties.Settings.Default.Password = textBox2.Text;
                Properties.Settings.Default.UserName = textBox1.Text;
            }
            else
            {
                Properties.Settings.Default.Password = "";
                Properties.Settings.Default.UserName = "";
            }
            Properties.Settings.Default.Save();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
            if (textBox1.Text == "" || textBox2.Text == "")
            {
                System.Media.SystemSounds.Beep.Play();
                return;

            }
            objSQLcommand.CommandText = "select * from Users where UserName=@";
            objSQLcommand.Parameters.Clear();
            objSQLcommand.Parameters.AddWithValue("@", textBox1.Text.ToLower());
            try
            {
                SqlDataReader DR = objSQLcommand.ExecuteReader();
                DR.Read();
                objSQLcommand.Parameters.Clear();
                if (DR.HasRows)
                {


                    if (DR[2].ToString() == Encrypt.EncryptStringAES(textBox2.Text,"X2"))
                    {
   
                        //GOTO Main Form With DR[0]
                        RememberTools();
                        MainForm frm = new MainForm(DR[0].ToString());
                        frm.Show();
                        
   
                
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("کلمه عبور صحیح نیست.\nاگر شما کلمه عبور خود را فراموش کرده اید نرم افزار می تواند به شما یاداوری کند", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        {
                            
            
                            textBox2.Text = "";
                            textBox2.Select();

                        }
  
                    }

                }
                else
                {
                    MessageBox.Show("اطلاعات صحیح نیست یا ممکن است همچین کاربری به ثبت نرسیده باشد:" + Environment.NewLine +  textBox1.Text , "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                if (DR.IsClosed == false)
                    DR.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            //Login

           
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Save all Setting
            RememberTools();
            Properties.Settings.Default.Save();
            Application.Exit();
        }


        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SendKeys.Send("{tab}");
            }
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                button1_Click(null, null);
            }
        }



        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                objSqlConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=" + DataDirectory + ";Integrated Security=True;User Instance=True");
                objSQLcommand = new SqlCommand();
                objSQLcommand.Connection = objSqlConnection;
                objSqlConnection.Open();
                button1.Enabled = true;
                lblWait.Visible = picWait.Visible = false;
                linkLabel1.Enabled = linkLabel2.Enabled = true;
            }
            catch (Exception EX)
            {
                MessageBox.Show(EX.Message+"\nPlease try later.", "Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                this.Close();
            }
        }

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

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

        private void menuItem3_Click_1(object sender, EventArgs e)
        {
            new Newuser().ShowDialog();
        }

        private void menuItem4_Click_1(object sender, EventArgs e)
        {
            new Password_Remember().ShowDialog();
        }

        private void menuItem6_Click_1(object sender, EventArgs e)
        {
            vistaPictureBox1.Image = Properties.Resources.Fower;
            Properties.Settings.Default.ImageDir = "";
            Properties.Settings.Default.Save();
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            OpenFileDialog O1 = new OpenFileDialog();
            O1.Title = "Select Image";
            O1.Filter = "Image Files|*.PNG;*.BMP;*.GIF;*.Jpg";
            if (O1.ShowDialog() == DialogResult.OK)
            {
                vistaPictureBox1.Image = Image.FromFile(O1.FileName);
                Properties.Settings.Default.ImageDir = O1.FileName;
                Properties.Settings.Default.Save();
            }
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("ایا می خواهید نرم افزار دفترچه تلفن پارس را ترک کنید؟", "Pars Contacts", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new Newuser().ShowDialog();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new Password_Remember().ShowDialog();
        }

        private void vistaPictureBox1_Load(object sender, EventArgs e)
        {

        }
        int i = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (i != 3)
            {
                lblWait.Text += ".";
                i += 1;
            }
            else
            {
                lblWait.Text = "در حال اتصال";
                i = 0;
            }

        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new About().ShowDialog();
        }

        private void imageButton1_Click(object sender, EventArgs e)
        {

        }




    }
}
