using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;

namespace Shopping
{
    public partial class frmPersonGroup : Form
    {

        private Int16 SelectedID = 0;
        private String SelectedTitle = string.Empty;
        private Boolean IsEditMode = false;

        public frmPersonGroup()
        {
            InitializeComponent();
        }

        private void frmPersonGroup_Load(object sender, EventArgs e)
        {
            LoadGrid();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!IsGroupTitleValid())
                return;

            SaveData();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (SelectedID == 0)
            {
                MessageBox.Show("ردیفی انتخاب نشده است", "پیغام", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            txtCode.Text = SelectedID.ToString();
            txtGroupTitle.Text = SelectedTitle;
            IsEditMode = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("آیا از حذف رکورد جاری مطمئن هستید؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                DeleteData();
                New();
            }
            else
            {
                MessageBox.Show("عملیات حذف کنسل شد", "پیام", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            New();
        }

        private void txtGroupTitle_Validating(object sender, CancelEventArgs e)
        {
            if (!IsGroupTitleValid())
            {
                myErrorProvider.SetIconAlignment((Control)sender, ErrorIconAlignment.MiddleLeft);
                myErrorProvider.SetError((Control)sender, "نام گروه را وارد کنید");
            }
            else
            {
                myErrorProvider.SetError((Control)sender, "");
            }
        }

        private void gridViewPersonGroup_RowClick(object sender, RowClickEventArgs e)
        {
            SelectedID = Convert.ToInt16(gridViewPersonGroup.GetDataRow(e.RowHandle)["PersonGroupID"]);
            SelectedTitle = gridViewPersonGroup.GetDataRow(e.RowHandle)["PersonGroupTitle"].ToString();
        }

        private void txtGroupTitle_EditValueChanged(object sender, EventArgs e)
        {
            if (txtGroupTitle.Text != string.Empty)
            {
                myErrorProvider.Clear();
            }
        }

        private void New()
        {
            SelectedID = 0;
            SelectedTitle = string.Empty;
            IsEditMode = false;
            txtCode.Text = txtGroupTitle.Text = string.Empty;
            myErrorProvider.Clear();
        }

        private void SaveData()
        {
            SqlConnection conn = new SqlConnection();

            try
            {
                conn.ConnectionString = @"data source =SOROUSH-PC\MYHEKATON2014 ; initial catalog = NikAmoozShop ; integrated security = true";

                string query = "";

                if (IsEditMode)
                    query = "UPDATE [Person].[PersonGroup] SET[PersonGroupTitle] = (N'" + txtGroupTitle.Text + "')" +
                            " WHERE PersonGroupID = '" + SelectedID + "'";
                else
                    query = "INSERT INTO [Person].[PersonGroup] ([PersonGroupTitle]) VALUES (N'" + txtGroupTitle.Text + "')";

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = query;
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();

                if (rowsAffected > 0)
                {
                    LoadGrid();
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("وقوع مشکل در هنگام کار با دیتایس" + "\n" + ex.Message, "خطای بانک اطلاعاتی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            catch (Exception ex)
            {
                MessageBox.Show("وقوع مشکل در سیستم" + "\n" + ex.Message, "خطای سیستمی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                conn.Close();
            }
        }

        private void DeleteData()
        {
            SqlConnection conn = new SqlConnection();

            try
            {
                if (SelectedID == 0)
                {
                    MessageBox.Show("ردیفی انتخاب نشده است", "پیغام", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                conn.ConnectionString = @"data source =SOROUSH-PC\MYHEKATON2014 ; initial catalog = NikAmoozShop ; integrated security = true";
                string query = "DELETE [Person].[PersonGroup] WHERE PersonGroupID = '" + SelectedID + "'";

                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = query;
                cmd.Connection = conn;
                conn.Open();
                int rowsAffected = cmd.ExecuteNonQuery();

                if (rowsAffected > 0)
                {
                    LoadGrid();
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("وقوع مشکل در هنگام کار با دیتایس" + "\n" + ex.Message, "خطای بانک اطلاعاتی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            catch (Exception ex)
            {
                MessageBox.Show("وقوع مشکل در سیستم" + "\n" + ex.Message, "خطای سیستمی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                conn.Close();
            }
        }

        private void LoadGrid()
        {
            SqlConnection conn = new SqlConnection();

            try
            {
                conn.ConnectionString = @"data source =SOROUSH-PC\MYHEKATON2014 ; initial catalog = NikAmoozShop ; integrated security = true";
                string query = " SELECT * FROM [Person].[PersonGroup]";
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = query;
                cmd.Connection = conn;
                conn.Open();

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    gridPersonGroups.DataSource = dt;
                }


            }
            catch (SqlException ex)
            {
                MessageBox.Show("وقوع مشکل در هنگام کار با دیتایس" + "\n" + ex.Message, "خطای بانک اطلاعاتی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            catch (Exception ex)
            {
                MessageBox.Show("وقوع مشکل در سیستم" + "\n" + ex.Message, "خطای سیستمی", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                conn.Close();
            }
        }

        private bool IsGroupTitleValid()
        {
            return txtGroupTitle.Text.Length > 0;
        }

    }
}
