using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using TinyHeels.App_Code;

namespace TinyHeels
{
    public partial class controlEmployee : UserControl
    {
        private static controlEmployee _instance;
        public static controlEmployee Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new controlEmployee();
                }
                return _instance;
            }
        }
        public controlEmployee()
        {
            InitializeComponent();
            cboGender.SelectedIndex = 0;
            cboLoginRole.SelectedIndex = 0;

            bindGrid();
        }
        public void bindGrid()
        {
            try
            {
                Employee emp = new Employee();
                DataTable dt = emp.getAllEmployee();
                DataGrid.DataSource = dt;
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Sorry Ubable to loadGrid");
                error.ShowDialog();
            }
        }
        byte[] imgBytes;
        private void loadImage(object sender, System.EventArgs e)
        {
            try
            {
                OpenFileDialog obj = new OpenFileDialog();
                obj.Filter = "Image Files (*.jpg)|*.jpg";
                obj.FilterIndex = 1;
                DialogResult file = obj.ShowDialog();
                if (file == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(obj.FileName);
                    this.imgBytes = imageToByteArray(Image.FromFile(obj.FileName));
                }
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Sorry Error To Upload Image");
                error.ShowDialog();
            }
        }

        // function to convert image to bytes got it from internet
        public byte[] imageToByteArray(System.Drawing.Image imgIn)
        {
            MemoryStream ms = new MemoryStream();
            imgIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string id = (string.IsNullOrWhiteSpace(txtId.Text)) ? "-" : txtId.Text;
                string name = (string.IsNullOrWhiteSpace(txtName.Text)) ? "-" : txtName.Text;
                string gender = cboGender.Text;
                string loginRole = cboLoginRole.Text;
                string phone = (string.IsNullOrWhiteSpace(txtPhone.Text)) ? "-" : txtPhone.Text;
                string email = (string.IsNullOrWhiteSpace(txtEmail.Text)) ? "-" : txtEmail.Text;
                string address = (string.IsNullOrWhiteSpace(txtAddress.Text)) ? "-" : txtAddress.Text;
                double bSalary = double.Parse((string.IsNullOrWhiteSpace(txtSalary.Text)) ? "0.0" : txtSalary.Text);
                bool status = (chkStatus.Checked == true) ? true : false;


                System.Drawing.Image imgx;
                Image ximgx = pictureBox1.Image;

                this.imgBytes = imageToByteArray(ximgx);


                if (name.Equals("-"))
                {
                    ErrorBox error = new ErrorBox("Do Provide Name Please");
                    error.ShowDialog();
                }
                else
                {
                    Employee emp = new Employee();
                    emp.EmpId = id;
                    emp.EmpName = name;
                    emp.EmpGender = gender;
                    emp.EmpPhone = phone;
                    emp.EmpEmail = email;
                    emp.EmpAddress = address;
                    emp.EmpLoginRole = loginRole;
                    // Actually default login and password is the employee id
                    // and i want them to be stored encrypted specially password
                    // so i have to use the pre defined class to encrypte which i downloaded from internet
                    emp.EmpLoginId = id;
                    emp.EmpLoginPassword = StringCipher.Encrypt("testkey", id);
                    emp.BSalary = bSalary;
                    emp.EmpStatus = status;
                    emp.Image = this.imgBytes;
                    emp.insertNewEmployee();

                    ErrorBox error = new ErrorBox("Done and Thank You");
                    error.ShowDialog();
                    resetData();
                }
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Sorry Error To Upload Data");
                error.ShowDialog();
            }
        }

        private void DataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (DataGrid.Rows.Count == 0)
                {
                    ErrorBox error = new ErrorBox("Sorry No Row Selected");
                    error.ShowDialog();
                }
                else
                {
                    string empID = DataGrid.SelectedRows[0].Cells[0].Value.ToString();
                    DataTable dt = new DataTable();
                    Employee obj = new Employee();
                    obj.EmpId = empID;
                    dt = obj.getSpecificEmployee();
                    txtId.Text = dt.Rows[0][0].ToString();
                    txtName.Text = dt.Rows[0][1].ToString();
                    string gender = dt.Rows[0][2].ToString();

                    int c = 0;
                    foreach (string str in cboGender.Items)
                    {
                        if (str == gender)
                        {
                            cboGender.SelectedIndex = c;
                        }
                        c++;
                    }
                    txtPhone.Text = dt.Rows[0][3].ToString();
                    txtAddress.Text = dt.Rows[0][4].ToString();
                    txtEmail.Text = dt.Rows[0][5].ToString();
                    string loginRole = dt.Rows[0][6].ToString();

                    c = 0;
                    foreach (string str in cboLoginRole.Items)
                    {
                        if (str == loginRole)
                        {
                            cboLoginRole.SelectedIndex = c;
                        }
                        c++;
                    }

                    txtSalary.Text = dt.Rows[0][9].ToString();
                    bool status = bool.Parse(dt.Rows[0][10].ToString());
                    if (status)
                        chkStatus.Checked = true;
                    else
                        chkStatus.Checked = false;
                    this.imgBytes = (Byte[])dt.Rows[0][11];
                    Image img = byteArrayToImage(this.imgBytes);
                    pictureBox1.Image = img;
                }
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Sorry Error To Load Data");
                error.ShowDialog();
            }
        }
        //A function to convert byte array to image
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
        public void resetData()
        {
            try
            {
                txtId.Text = "-";
                txtName.Text = "";
                txtAddress.Text = "";
                txtPhone.Text = "";
                txtEmail.Text = "";
                txtSalary.Text = "0";
                cboGender.SelectedIndex = 0;
                cboLoginRole.SelectedIndex = 0;
                pictureBox1.Image = TinyHeels.Properties.Resources._default;
            }
            catch (Exception ex)
            {
                throw new Exception("Could not reset data");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                resetData();
                bindGrid();
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox(ex.Message);
                error.ShowDialog();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string id = DataGrid.SelectedRows[0].Cells[0].Value.ToString();
                ManagePayroll obj = new ManagePayroll(id);
                obj.ShowDialog();
            }
            catch (Exception ex)
            {

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (DataGrid.Rows.Count == 1)
                {
                    ErrorBox error = new ErrorBox("No Data Selected or The Last Item");
                    error.ShowDialog();
                }
                else
                {
                    YesNo y = new YesNo("Are You Sure To Delete?");
                    y.ShowDialog();
                    if (Common.command == true)
                    {
                        string id = DataGrid.SelectedRows[0].Cells[0].Value.ToString();
                        Employee emp = new Employee();
                        emp.EmpId = id;
                        emp.deleteEmployee();
                        ErrorBox error = new ErrorBox("Delete Thanx");
                        error.ShowDialog();
                        resetData();
                        bindGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox(ex.Message);
                error.ShowDialog();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string empId = DataGrid.SelectedRows[0].Cells[0].Value.ToString();
                Employee obj = new Employee();
                obj.EmpId = empId;
                YesNo ays = new YesNo("Are you sure want to reset?");
                ays.ShowDialog();
                if (Common.command == true)
                {
                    obj.EmpLoginId = empId;
                    obj.EmpLoginPassword = StringCipher.Encrypt("testkey", empId);
                    obj.reset();
                    ErrorBox d = new ErrorBox("Done");
                    d.ShowDialog();
                }
                resetData();
                bindGrid();
            }
            catch (Exception ex)
            {
                ErrorBox obj = new ErrorBox("Error! SELECT && Try  Again");
                obj.ShowDialog();
            }
        }
        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog obj = new OpenFileDialog();
                obj.Filter = "Image Files (*.jpg)|*.jpg";
                obj.FilterIndex = 1;
                DialogResult file = obj.ShowDialog();
                if (file == DialogResult.OK)
                {
                    pictureBox1.Image = Image.FromFile(obj.FileName);
                    this.imgBytes = imageToByteArray(Image.FromFile(obj.FileName));
                }
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Sorry Error To Upload Image");
                error.ShowDialog();
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void change(object sender, EventArgs e)
        {
            ChangeCredentials obj = new ChangeCredentials();
            obj.ShowDialog();
        }
    }
}
