using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Formats.Asn1;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//using CsvReadWrite;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Drawing.Imaging;
using PackingControlSystem.lib;
using System.Diagnostics.SymbolStore;
using System.Management;

namespace PackingControlSystem
{
    public partial class frmPart : Form
    {
        private List<List<string>> Settings = new List<List<string>>();
        DataTable dtPart = new DataTable();
        DataTable dtPartSelect = new DataTable();
        DataTable dtPartNoSelect = new DataTable();
        DataTable dtCustomer = new DataTable();
        private Image returnImage;
        private string rowID = string.Empty;
        private string partNo = string.Empty;
        private string userName = string.Empty;


        public frmPart(string systemUserName)
        {
            InitializeComponent();
            userName = systemUserName;
        }

        private void txtPartNO_TextChanged(object sender, EventArgs e)
        {

        }

        public string RtnDbCon()
        {
            return "Data Source=" + this.Settings[0][0] + ";Initial Catalog=" + this.Settings[0][1] + ";User Id=sa;Password=" + this.Settings[0][2] + ";";

        }

        private void frmPart_Load(object sender, EventArgs e)
        {
            List<string> tmp = null;
            dgvPart.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            //listBox1.HorizontalScrollbar = true;
            Settings = new List<List<string>>();
            tmp = null;
            using (var csv = new CsvReader(System.IO.Directory.GetCurrentDirectory() + "\\Settings.csv"))
            {
                while ((tmp = csv.ReadRow()) != null)
                {
                    Settings.Add(tmp);

                }

            }//using end

            loadTable();

            SetCustomer();

            SettxtReadOnly();

        }

        private void SetCustomer()
        {
            dtCustomer = new DataTable();
            clsUtil_MSSQL.GetDataFromTBCustomer(RtnDbCon(), "TM_CUSTOMER", ref dtCustomer);
            for (int i = 0; i < dtCustomer.Rows.Count; i++)
            {
                cbbCustomer.Items.Add(dtCustomer.Rows[i][0].ToString() + " | " + dtCustomer.Rows[i][1].ToString());
            }

            cbbCustomer.SelectedItem = dtCustomer.Rows[0][0].ToString() + " | " + dtCustomer.Rows[0][1].ToString();
        }

        private void SelectCustomer(string cusID)
        {
            dtCustomer = new DataTable();
            clsUtil_MSSQL.GetDataFromTBCustomer(RtnDbCon(), "TM_CUSTOMER", ref dtCustomer);
            for (int i = 0; i < dtCustomer.Rows.Count; i++)
            {

                if (dtCustomer.Rows[i][0].ToString() == cusID)
                {
                    cbbCustomer.SelectedItem = dtCustomer.Rows[i][0].ToString() + " | " + dtCustomer.Rows[i][1].ToString();
                }
            }

        }

        private void SettxtReadOnly()
        {
            txtPartID.ReadOnly = true;
            txtModel.ReadOnly = true;
            txtModelCode.ReadOnly = true;
            txtPartName.ReadOnly = true;
            txtCustomerPartName.ReadOnly = true;
            txtPartNO.ReadOnly = true;
            txtCustomerPartNO.ReadOnly = true;
            txtDetail.ReadOnly = true;
            nudQTY.ReadOnly = true;
            nudCircleTime.ReadOnly = true;
            nudDryLifeTime.ReadOnly = true;
            nudWetLifeTime.ReadOnly = true;
            nudQRLength.ReadOnly = true;
            txtLocation.ReadOnly = true;
            nudModelStart.ReadOnly = true;
            nudModelLength.ReadOnly = true;
            nudDateStart.ReadOnly = true;
            nudDateLength.ReadOnly = true;
            txtPackaging.ReadOnly = true;
            cbbCustomer.Enabled = false;
            txtPhotoSpec1.ReadOnly = true;
            txtPhotoSpec2.ReadOnly = true;
            btnPhotoSpec1.Enabled = false;
            btnPhotoSpec2.Enabled = false;
            btnSave.Enabled = false;
            btnClear.Enabled = false;
            btnAdd.Enabled = true;
            cbbSIDE.Enabled = false;
            cbbType.Enabled = false;
            txtWet.Enabled = false;
        }

        private void SettxtStart()
        {
            txtPartID.Text = string.Empty;
            txtModel.Text = string.Empty;
            txtModelCode.Text = string.Empty;
            txtPartName.Text = string.Empty;
            txtCustomerPartName.Text = string.Empty;
            txtPartNO.Text = string.Empty;
            txtCustomerPartNO.Text = string.Empty;
            txtDetail.Text = string.Empty;
            nudQTY.Text = "0";
            nudCircleTime.Text = "0";
            nudDryLifeTime.Text = "0";
            nudWetLifeTime.Text = "0";
            nudQRLength.Text = "0";
            txtLocation.Text = string.Empty;
            nudModelStart.Text = "0";
            nudModelLength.Text = "0";
            nudDateStart.Text = "0";
            nudDateLength.Text = "0";
            txtPackaging.Text = string.Empty;
            txtPhotoSpec1.Text = string.Empty;
            txtPhotoSpec2.Text = string.Empty;
            pbPhotoSpec1.Image = null;
            pbPhotoSpec2.Image = null;
            //pbPhotoSpec1.Controls.Clear();
            //pbPhotoSpec2.Controls.Clear();
            btnDelete.Enabled = true;
            cbbSIDE.Text = string.Empty;
            cbbType.Text = "Dry";
            txtWet.Text = string.Empty;
        }

        private void SettxtWrite()
        {
            txtPartNO.BackColor = SystemColors.Window;
            txtPartID.ReadOnly = false;
            txtModel.ReadOnly = false;
            txtModelCode.ReadOnly = false;
            txtPartName.ReadOnly = false;
            txtCustomerPartName.ReadOnly = false;
            txtPartNO.ReadOnly = false;
            txtCustomerPartNO.ReadOnly = false;
            txtDetail.ReadOnly = false;
            nudQTY.ReadOnly = false;
            nudCircleTime.ReadOnly = false;
            nudDryLifeTime.ReadOnly = false;
            nudWetLifeTime.ReadOnly = false;
            nudQRLength.ReadOnly = false;
            txtLocation.ReadOnly = false;
            nudModelStart.ReadOnly = false;
            nudModelLength.ReadOnly = false;
            nudDateStart.ReadOnly = false;
            nudDateLength.ReadOnly = false;
            txtPackaging.ReadOnly = false;
            cbbCustomer.Enabled = true;
            btnPhotoSpec1.Enabled = true;
            btnPhotoSpec2.Enabled = true;
            btnAdd.Enabled = false;
            btnSave.Enabled = true;
            btnClear.Enabled = true;
            //btnDelete.Enabled = false;
            cbbSIDE.Enabled = true;
            cbbType.Enabled = true;
            if (cbbType.Text == "Dry")
            {
                txtWet.Enabled = false;
            }
            else
            {
                txtWet.Enabled = true;
            }

        }



        private void dgvPart_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // Add row number
            (sender as DataGridView).Rows[e.RowIndex].HeaderCell.Value = (e.RowIndex + 1).ToString();

            int idx = e.RowIndex;
            DataGridViewRow row = dgvPart.Rows[idx];
            row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;


        }

        private void dgvPart_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dgvPart_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SettxtWrite();

            txtPartNO.ReadOnly = true;
            txtPartNO.BackColor = Color.WhiteSmoke;

            dtPartSelect = new DataTable();
            int rowindex = dgvPart.CurrentRow.Index;
            clsUtil_MSSQL.GetDataFromTBSelect(RtnDbCon(), "TM_PARTS", ref dtPartSelect, dgvPart[5, rowindex].Value.ToString(), dgvPart[2, rowindex].Value.ToString());
            rowID = dgvPart[5, rowindex].Value.ToString();
            partNo = dgvPart[2, rowindex].Value.ToString();
            txtPartID.Text = dtPartSelect.Rows[0][1].ToString();
            txtModel.Text = dtPartSelect.Rows[0][2].ToString();
            txtModelCode.Text = dtPartSelect.Rows[0][3].ToString();
            txtPartName.Text = dtPartSelect.Rows[0][4].ToString();
            txtCustomerPartName.Text = dtPartSelect.Rows[0][5].ToString();
            txtPartNO.Text = dtPartSelect.Rows[0][6].ToString();
            txtCustomerPartNO.Text = dtPartSelect.Rows[0][7].ToString();
            nudQTY.Text = dtPartSelect.Rows[0][8].ToString();
            nudCircleTime.Text = dtPartSelect.Rows[0][9].ToString();
            nudDryLifeTime.Text = dtPartSelect.Rows[0][10].ToString();
            nudWetLifeTime.Text = dtPartSelect.Rows[0][11].ToString();
            //cbbCustomer.Text = dtPartSelect.Rows[0][13].ToString();
            SelectCustomer(dtPartSelect.Rows[0][13].ToString());
            nudQRLength.Text = dtPartSelect.Rows[0][12].ToString();
            txtLocation.Text = dtPartSelect.Rows[0][21].ToString();
            nudModelStart.Text = dtPartSelect.Rows[0][23].ToString();
            nudModelLength.Text = dtPartSelect.Rows[0][24].ToString();
            txtDetail.Text = dtPartSelect.Rows[0][25].ToString();
            nudDateStart.Text = dtPartSelect.Rows[0][26].ToString();
            nudDateLength.Text = dtPartSelect.Rows[0][27].ToString();
            txtPackaging.Text = dtPartSelect.Rows[0][22].ToString();
            if (dtPartSelect.Rows[0][30].ToString() == "")
            {
                cbbSIDE.Text = " ";
            }
            else
            {
                cbbSIDE.Text = dtPartSelect.Rows[0][30].ToString();
            }
            cbbType.Text = dtPartSelect.Rows[0][31].ToString();
            txtWet.Text = dtPartSelect.Rows[0][32].ToString();
            txtPhotoSpec1.Text = string.Empty;
            txtPhotoSpec2.Text = string.Empty;
            pbPhotoSpec1.Image = null;
            pbPhotoSpec2.Image = null;
            //pbPhotoSpec1.Controls.Clear();
            //pbPhotoSpec2.Controls.Clear();

            if (dtPartSelect.Rows[0][28] != System.DBNull.Value)
            {
                pbPhotoSpec1.Image = byteArrayToImage((byte[])dtPartSelect.Rows[0][28]);
            }

            if (dtPartSelect.Rows[0][29] != System.DBNull.Value)
            {
                pbPhotoSpec2.Image = byteArrayToImage((byte[])dtPartSelect.Rows[0][29]);
            }


        }


        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            System.Drawing.Bitmap bitmap = null;
            ImageConverter converter = new ImageConverter();
            System.Drawing.Image img =
            (System.Drawing.Image)converter.ConvertFrom(byteArrayIn);
            bitmap = (System.Drawing.Bitmap)img;
            return bitmap;
        }

        private void btnPhotoSpec1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";

            this.openFileDialog1.Multiselect = false;
            this.openFileDialog1.Title = "Select Photos";

            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                    try
                    {
                        PictureBox imageControl = new PictureBox();
                        imageControl.Height = 800;
                        imageControl.Width = 1100;

                        Image.GetThumbnailImageAbort myCallback =
                                new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        Bitmap myBitmap = new Bitmap(file);
                        Image myThumbnail = myBitmap.GetThumbnailImage(1100, 800,
                            myCallback, IntPtr.Zero);
                        imageControl.Image = myThumbnail;

                        pbPhotoSpec1.Image = myThumbnail;
                        //pbPhotoSpec1.Controls.Add(imageControl);
                        txtPhotoSpec1.Text = file;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }
        }

        public bool ThumbnailCallback()
        {
            return false;
        }

        private void btnPhotoSpec2_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter =
"Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" +
"All files (*.*)|*.*";

            this.openFileDialog1.Multiselect = false;
            this.openFileDialog1.Title = "Select Photos";

            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                    try
                    {
                        PictureBox imageControl = new PictureBox();
                        imageControl.Height = 400;
                        imageControl.Width = 400;

                        Image.GetThumbnailImageAbort myCallback =
                                new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        Bitmap myBitmap = new Bitmap(file);
                        Image myThumbnail = myBitmap.GetThumbnailImage(300, 300,
                            myCallback, IntPtr.Zero);
                        imageControl.Image = myThumbnail;

                        pbPhotoSpec2.Image = null;
                        pbPhotoSpec2.Controls.Add(imageControl);
                        txtPhotoSpec2.Text = file;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            SettxtWrite();
            btnDelete.Enabled = false;
            rowID = string.Empty;
            partNo = string.Empty;
            txtPartID.Focus();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            SettxtReadOnly();
            SettxtStart();
            SetCustomer();
            rowID = string.Empty;
            partNo = string.Empty;
        }

        public byte[] ConvertImgtoByte(Image image)
        {
            Image img = image;
            byte[] arr;
            ImageConverter converter = new ImageConverter();
            arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
            if (image == null)
            {
                arr = null;
            }
            return arr;


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtPartNO.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, "กรุณาใส่ข้อมูล Part NO. ก่อนบันทึก",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (txtCustomerPartNO.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, "กรุณาใส่ข้อมูล Customer Part NO. ก่อนบันทึก",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (cbbSIDE.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, "กรุณาใส่ข้อมูล SIDE ก่อนบันทึก",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (cbbType.Text.Trim() == "Wet" && txtWet.Text.Trim() == string.Empty)
            {
                MessageBox.Show(this, "กรุณาใส่ข้อมูล Wet ก่อนบันทึก",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (cbbType.Text.Trim() == "Wet" && txtWet.Text.Trim().Length != 4)
            {
                MessageBox.Show(this, "กรุณาใส่ข้อมูล Wet ให้ครบจำนวน 4 digit",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }


            List<string> tmp;
            tmp = new List<string>();
            tmp = cbbCustomer.Text.Split("|").ToList();


            if (rowID != string.Empty && partNo != string.Empty)
            {
                int introwID = Convert.ToInt32(rowID);
                clsUtil_MSSQL.updatePart(RtnDbCon(), introwID, txtPartID.Text, txtModel.Text, txtModelCode.Text, txtPartName.Text,
                    txtCustomerPartName.Text, partNo, txtCustomerPartNO.Text, Convert.ToInt32(nudQTY.Value), Convert.ToInt32(nudCircleTime.Value), Convert.ToInt32(nudDryLifeTime.Value),
                    Convert.ToInt32(nudWetLifeTime.Value), Convert.ToInt32(nudQRLength.Value), tmp[0].Trim(), userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"),
                    txtLocation.Text, Convert.ToInt32(nudModelStart.Value), Convert.ToInt32(nudModelLength.Value),
                    Convert.ToInt32(nudDateStart.Value), Convert.ToInt32(nudDateLength.Value), txtPackaging.Text, ConvertImgtoByte(pbPhotoSpec1.Image), ConvertImgtoByte(pbPhotoSpec2.Image),
                    cbbSIDE.Text, cbbType.Text, txtWet.Text, txtDetail.Text);

                MessageBox.Show(this, "แก้ไขข้อมูล Part Information เรียบร้อย",
                                   "Part Information", MessageBoxButtons.OK,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button1, 0);

                loadTable();

                SettxtReadOnly();
                SettxtStart();
                SetCustomer();
                rowID = string.Empty;
                partNo = string.Empty;

            }

            else if ((rowID == string.Empty) && (txtPartNO.Text != string.Empty))
            {
                partNo = txtPartNO.Text;

                dtPartNoSelect = new DataTable();
                clsUtil_MSSQL.GetDataFromTBPartNoSelect(RtnDbCon(), "TM_PARTS", ref dtPartNoSelect, partNo);
                if (dtPartNoSelect.Rows.Count > 0)
                {
                    MessageBox.Show(this, "ไม่สามารถเพิ่มข้อมูล Part Information ได้ เนื่องจาก Part No นี่มีอยู่แล้วในระบบ",
                                   "Part Information", MessageBoxButtons.OK,
                                   MessageBoxIcon.Error,
                                   MessageBoxDefaultButton.Button1, 0);
                    return;
                }


                clsUtil_MSSQL.insertPart(RtnDbCon(), txtPartID.Text, txtModel.Text, txtModelCode.Text, txtPartName.Text,
                    txtCustomerPartName.Text, partNo, txtCustomerPartNO.Text, userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), userName, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"),
                Convert.ToInt32(nudQTY.Value), Convert.ToInt32(nudCircleTime.Value), Convert.ToInt32(nudDryLifeTime.Value),
                    Convert.ToInt32(nudWetLifeTime.Value), Convert.ToInt32(nudQRLength.Value), tmp[0].Trim(), txtLocation.Text,
                    Convert.ToInt32(nudModelStart.Value), Convert.ToInt32(nudModelLength.Value),
                    Convert.ToInt32(nudDateStart.Value), Convert.ToInt32(nudDateLength.Value), txtPackaging.Text,
                    cbbSIDE.Text, cbbType.Text, txtWet.Text, txtDetail.Text);

                dtPartSelect = new DataTable();
                clsUtil_MSSQL.GetDataFromTBSelectMaxID(RtnDbCon(), "TM_PARTS", ref dtPartSelect);
                rowID = dtPartSelect.Rows[0][0].ToString();


                clsUtil_MSSQL.insertPartFile(RtnDbCon(), rowID, partNo, ConvertImgtoByte(pbPhotoSpec1.Image), ConvertImgtoByte(pbPhotoSpec2.Image));

                MessageBox.Show(this, "เพิ่มข้อมูล Part Information เรียบร้อย",
                                   "Part Information", MessageBoxButtons.OK,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button1, 0);

                loadTable();

                SettxtReadOnly();
                SettxtStart();
                SetCustomer();
                rowID = string.Empty;
                partNo = string.Empty;

            }

        }

        private void loadTable()
        {
            dtPart = new DataTable();
            clsUtil_MSSQL.GetDataFromTB(RtnDbCon(), "TM_PARTS", ref dtPart);
            dgvPart.DataSource = dtPart;
            //dgvPart.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            dgvPart.RowHeadersWidth = 70;

            for (int i = 0; i < dgvPart.Rows.Count; i++)
            {
                if (i % 2 != 0)
                {

                    dgvPart.Rows[i].DefaultCellStyle.BackColor = SystemColors.ControlLight;

                }
                else
                {


                }

            }


        }



        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (txtPartNO.Text == string.Empty)
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่จะลบก่อน",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }


            DialogResult dialogResult = MessageBox.Show(this, "ท่านต้องการที่ลบรายการนี้แน่ใจหรือไม่?",
                                   "Part Information", MessageBoxButtons.YesNo,
                                   MessageBoxIcon.Question,
                                   MessageBoxDefaultButton.Button1, 0);

            if (dialogResult == DialogResult.Yes)
            {
                if (rowID != string.Empty && partNo != string.Empty)
                {
                    int introwID = Convert.ToInt32(rowID);
                    clsUtil_MSSQL.deletePart(RtnDbCon(), introwID, partNo);

                    MessageBox.Show(this, "ลบข้อมูลรายการนี้เรียบร้อย",
                                       "Part Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Information,
                                       MessageBoxDefaultButton.Button1, 0);

                    loadTable();

                    SettxtReadOnly();
                    SettxtStart();
                    SetCustomer();
                    rowID = string.Empty;
                    partNo = string.Empty;
                }
                else if (dialogResult == DialogResult.No)
                {
                    return;
                }



            }
        }

        private void cbbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbType.Text == "Dry")
            {
                txtWet.Enabled = false;
            }
            else
            {
                txtWet.Enabled = true;
            }
        }
    }
}
