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.Globalization;
using FMessegeBox;
using System.IO.Ports;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication8
{
    public partial class frmMain : Form
    {
        string id = "-1";
        int row_index = -1;
        string srch = "TLname";

        // ذخیره شماره برای تماس
        string cTell = string.Empty;
        string cFax = string.Empty;
        string cMobile = string.Empty;
        //
        string EmailSelect = "";
        bool Email = false;
        //

        //بررسی اتصال به اینترنت
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        bool IsConnectedToInternet()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }
        //

        public frmMain()
        {
            InitializeComponent();
        }

        private void Tell_Load(object sender, EventArgs e)
        {
            MaximizeBox = false;
            ////
            //if (File.Exists(Application.StartupPath + "\\Setting.txt"))
            //{
            //    FileInfo file = new FileInfo(Application.StartupPath + "\\Setting.ini");
            //    file.Attributes = FileAttributes.Normal;
            //}
            //if (File.Exists(Application.StartupPath + "\\ServerInfo.txt"))
            //{
            //    FileInfo file = new FileInfo(Application.StartupPath + "\\ServerInfo.ini");
            //    file.Attributes = FileAttributes.Normal;
            //}
            ////

            ClsSetting c = new ClsSetting();
            c.GetSettingInfo();

            lblDate.Text = ClsSetting.DateIran(true);

            try
            {
                InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("fa-IR"));
            }
            catch
            {
                InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new CultureInfo("en-US"));
                FarsiMessegeBox.Show("زبان فارسی نصب نیست", "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
            }

            ConnectionInfo CI = new ConnectionInfo();
            CI.ConnectDB_Info();

            datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl where ID=-1").Tables[0];

            //
            datagridviewtell.Columns["ID"].HeaderText = "شماره کاربر";
            //datagridviewtell.Columns["ID"].Visible = false;
            datagridviewtell.Columns["TTitle"].HeaderText = "عنوان";
            datagridviewtell.Columns["TTitle"].Width = 65;
            datagridviewtell.Columns["TName"].HeaderText = "نام";
            datagridviewtell.Columns["TLname"].HeaderText = "نام خانوادگی";
            datagridviewtell.Columns["TCompany"].HeaderText = "شرکت";
            datagridviewtell.Columns["TTell"].HeaderText = "تلفن";
            datagridviewtell.Columns["TFax"].HeaderText = "فکس";
            datagridviewtell.Columns["TMobile"].HeaderText = "موبایل";
            datagridviewtell.Columns["TAdress"].HeaderText = "آدرس";
            datagridviewtell.Columns["TAdress"].MinimumWidth = 200;
            datagridviewtell.Columns["Email"].HeaderText = "ایمیل";
            datagridviewtell.Columns["Email"].MinimumWidth = 150;
            //

            datagridviewtell.MultiSelect = false;


            if (!Directory.Exists(Application.StartupPath + "\\SQL Backup"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\SQL Backup");
            }

            txtId.Focus();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            switch (comboSearchKeyboard.SelectedItem.ToString())
            {
                case "نام":
                    srch = "TName";
                    ds = ConnectionInfo.GetTable("select * from TellTbl where " + srch + " like '" + txtsrch.Text + "%' order by  TLname,TName");
                    break;

                case "نام خانوادگی":
                    srch = "TLname";
                    ds = ConnectionInfo.GetTable("select * from TellTbl where " + srch + " like '" + txtsrch.Text + "%' order by  TLname,TName");
                    break;

                case "شرکت":
                    srch = "TCompany";
                    ds = ConnectionInfo.GetTable("select * from TellTbl where " + srch + " like '" + txtsrch.Text + "%' order by  TLname,TName");
                    break;
            }
            datagridviewtell.DataSource = ds.Tables[0];
        }

        private void txtsrch_TextChanged(object sender, EventArgs e)
        {
            if (txtsrch.Text == "")
            {
                datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl where ID=-1").Tables[0];
            }
            else
            {
                datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl where " + srch + " like '" + txtsrch.Text + "%' order by  TLname,TName").Tables[0];
            }

        }

        private void button33_Click(object sender, EventArgs e)
        {
            datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl order by  TLname,TName").Tables[0];
            txtsrch.Text = "";
        }

        private void search_Click(object sender, EventArgs e)
        {


            datagridviewtell.DataSource = ConnectionInfo.GetTable(
                "select *  from TellTbl where TName like '" + txtname.Text
                + "%' and TLname like '" + txtlname.Text
                + "%' and TCompany like '" + txtcompany.Text
                + "%' and TTell like '" + txttell.Text
                + "%' and TFax like '" + txtfax.Text
                + "%' and TMobile like '" + txtmobile.Text
                + "%' and TAdress like '" + txtadress.Text
                + "%' order by  TLname,TName").Tables[0];

            txtsrch.Text = "";
        }

        #region Keyboard Textbox
        private void button1_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ا";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ب";
        }

        private void button5_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "پ";
        }

        private void button7_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ت";
        }

        private void button9_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ث";
        }

        private void button17_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ج";
        }

        private void button26_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "چ";
        }

        private void button15_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ح";
        }

        private void button13_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "خ";
        }

        private void button11_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "د";
        }

        private void button19_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ذ";
        }

        private void button20_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ر";
        }

        private void button23_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ز";
        }

        private void button32_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ژ";
        }

        private void button30_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "س";
        }

        private void button28_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ش";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ص";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ض";
        }

        private void button6_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ط";
        }

        private void button8_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ظ";
        }

        private void button18_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ع";
        }

        private void button16_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "غ";
        }

        private void button14_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ف";
        }

        private void button12_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ق";
        }

        private void button10_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ک";
        }

        private void button21_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "گ";
        }

        private void button22_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ل";
        }

        private void button24_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ن";
        }

        private void button29_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "و";
        }

        private void button27_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ه";
        }

        private void button25_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "ی";
        }

        private void button31_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "آ";
        }

        private void button34_Click(object sender, EventArgs e)
        {
            txtsrch.Text += "م";
        }
        #endregion

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd fAdd = new frmAdd();
            fAdd.ShowDialog();

            datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl order by  TLname,TName").Tables[0];
        }

        private void datagridviewtell_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (Convert.ToInt32(id) > 0)
                {
                    datagridviewtell.Rows[row_index].DefaultCellStyle.BackColor = Color.Empty;
                }

                id = datagridviewtell["ID", e.RowIndex].Value.ToString();
                row_index = e.RowIndex;

                cTell = datagridviewtell["TTell", e.RowIndex].Value.ToString();
                cFax = datagridviewtell["TFax", e.RowIndex].Value.ToString();
                cMobile = datagridviewtell["TMobile", e.RowIndex].Value.ToString();
            }
            catch
            {
                id = "-1";
                row_index = -1;
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (Convert.ToInt32(id) > 0)
                {
                    datagridviewtell.Rows[row_index].DefaultCellStyle.BackColor = Color.Aquamarine;

                    FrmEdit frmedit = new FrmEdit();
                    frmedit.idnum_ = id;
                    frmedit.ShowDialog();

                    datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl order by  TLname,TName").Tables[0];
                }
                else
                {
                    FarsiMessegeBox.Show("لطفا فیلد مورد نظر خود را انتخاب کنید", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                }
            }
            catch
            {
                FarsiMessegeBox.Show("لطفا فیلد مورد نظر خود را انتخاب کنید", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);

            }


        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(id) > 0)
            {
                datagridviewtell.Rows[row_index].DefaultCellStyle.BackColor = Color.Pink;

                DialogResult dr = FarsiMessegeBox.Show("آیا مطمئن هستید میخواهید این فیلد حذف شود ؟", "اخطار", FMessegeBoxButtons.YesNo, FMessegeBoxIcons.Question);

                if (dr == DialogResult.Yes)
                {

                    ConnectionInfo.QueryRun("delete from TellTbl where id=" + id + "'");

                    datagridviewtell.DataSource = ConnectionInfo.GetTable("select * from TellTbl order by  TLname,TName").Tables[0];

                    id = "-1";
                    row_index = -1;
                }
                else
                {
                    datagridviewtell.Rows[row_index].DefaultCellStyle.BackColor = Color.Empty;
                    id = "-1";
                    row_index = -1;
                }
            }
            else
            {
                FarsiMessegeBox.Show("لطفا فیلد مورد نظر خود را انتخاب کنید", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
            }
        }

        private void btnCall_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(id) > 0)
            {
                datagridviewtell.Rows[row_index].DefaultCellStyle.BackColor = Color.Aquamarine;

                SerialPort port = new SerialPort();
                try
                {
                    port.PortName = ClsSetting.ModemPortName_;
                    port.Open();
                    port.Write("AT\r");
                    Thread.Sleep(200);
                    port.Close();

                    frmCallSetting f = new frmCallSetting();
                    f.cFax_ = cFax;
                    f.cMobile_ = cMobile;
                    f.cTell_ = cTell;
                    f.ShowDialog();

                }
                catch
                {
                    FarsiMessegeBox.Show("پورت مورد نظر خراب است یا مودم وجود ندارد.", "خطا", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);
                }
                finally
                {
                    port.Close();
                }
            }
            else
            {
                FarsiMessegeBox.Show("لطفا فیلد مورد نظر خود را انتخاب کنید", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
            }

        }

        private void txttell_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\b')  //Back Space
                return;

            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                e.Handled = true;
                Console.Beep();
            }
        }

        private void txtfax_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\b')  //Back Space
                return;

            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                e.Handled = true;
                Console.Beep();
            }
        }

        private void txtmobile_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\b')  //Back Space
                return;

            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                e.Handled = true;
                Console.Beep();
            }
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            frmPassword f = new frmPassword();
            f.ShowDialog();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ClsSetting.Backup_A)  //انجام عمل پشتیبانگیری هر روز
            {
                ClsSetting.BackupDatabase_A();
            }

            ////مخفی کردن فایل های تنظیمات
            //if (File.Exists(Application.StartupPath + "\\Setting.txt"))
            //{
            //    FileInfo file = new FileInfo(Application.StartupPath + "\\Setting.ini");
            //    file.Attributes = FileAttributes.Hidden;
            //}
            //if (File.Exists(Application.StartupPath + "\\ServerInfo.txt"))
            //{
            //    FileInfo file = new FileInfo(Application.StartupPath + "\\ServerInfo.ini");
            //    file.Attributes = FileAttributes.Hidden;
            //}

            timerClose.Start();
            e.Cancel = true;

        }

        private void timerClock_Tick(object sender, EventArgs e)
        {
            lblTime.Text = ClsSetting.ToPersianNumber(DateTime.Now.ToLongTimeString());
        }

        private void datagridviewtell_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            lblRowsCount.Text = ClsSetting.ToPersianNumber(datagridviewtell.RowCount.ToString());
        }

        private void txtId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                datagridviewtell.DataSource = ConnectionInfo.GetTable("select *  from TellTbl where ID='" + txtId.Text + "'").Tables[0];
                txtsrch.Text = "";
                txtId.Text = "";
            }
        }

        private void timerClose_Tick(object sender, EventArgs e)
        {
            if (Opacity == 0)
            {
                Application.ExitThread();
            }
            Opacity -= 0.1;
        }

        private void btnEmail_Click(object sender, EventArgs e)
        {
            if (ClsSetting.EmailUserid != "" && ClsSetting.EmailPassword != "")
            {
                if (IsConnectedToInternet())
                {
                    if (!Email)
                    {
                        DialogResult dr = FarsiMessegeBox.Show("آیا مایلید از دفترچه تلفن شما هم انتخاب شود ؟", "", FMessegeBoxButtons.YesNo, FMessegeBoxIcons.Question);
                        if (dr == DialogResult.Yes)
                        {
                            FarsiMessegeBox.Show("لطفا شماره های خود را انتخاب کنید و دوباره دکمه ایمیل را فشار دهید", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                            Email = true;

                            datagridviewtell.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                            datagridviewtell.MultiSelect = true;
                            chkboxSellectAll.Visible = true;
                        }
                        else
                        {
                            frmEmail f = new frmEmail();
                            f.ShowDialog();
                            
                        }
                    }
                    else
                    {
                        Email = false;
                        foreach (DataGridViewRow dr in datagridviewtell.Rows)
                        {
                            if (dr.Selected)
                            {
                                EmailSelect += datagridviewtell["Email", dr.Index].Value.ToString() + " , ";
                            }
                        }
                        frmEmail f = new frmEmail();
                        f.EmailTo = EmailSelect;
                        f.ShowDialog();
                        chkboxSellectAll.Visible = false;
                        datagridviewtell.MultiSelect = false;
                        datagridviewtell.SelectionMode = DataGridViewSelectionMode.CellSelect;
                    }
                }
                else
                {
                    FarsiMessegeBox.Show("لطفا به اینترنت متصل شوید.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Information);
                }
            }
            else
            {
                FarsiMessegeBox.Show("لطفا ایمیل خود را در تنظیمات ثبت کنید.", "", FMessegeBoxButtons.Ok, FMessegeBoxIcons.Error);

            }
        }

        private void chkboxSellectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkboxSellectAll.Checked)
            {
                foreach (DataGridViewRow dr in datagridviewtell.Rows)
                {
                    dr.Selected = true;
                }
            }
        }
    }
}