using ManualSoftwareSystem.Inspection_Work;
using ManualSoftwareSystem.lib;
using ManualSoftwareSystem.Master_Maintenance;
using ManualSoftwareSystem.Operation_Manual;
//using Microsoft.Office.Interop.Excel;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using static System.Net.Mime.MediaTypeNames;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using Image = System.Drawing.Image;

namespace ManualSoftwareSystem
{
    public partial class FrmMasterMaintenanceDetail : Form
    {
        private List<List<string>> Master = new List<List<string>>();
        private string csvPartFile = string.Empty;
        private string csvPartFileSaveAs = string.Empty;
        public static string conditionForSave = string.Empty;
        public static string inputComment = string.Empty;
        public static string inputValue1 = string.Empty;
        public static string inputValue2 = string.Empty;
        public static string strUnit = string.Empty;
        public static bool isCancel = false;
        private string loginUser = string.Empty;
        public dynamic objLanguage;
        public static string picturePartFile = string.Empty;


        public FrmMasterMaintenanceDetail(string pathFile, string loginUser)
        {
            InitializeComponent();
            this.csvPartFile = pathFile;
            this.loginUser = loginUser;
            this.objLanguage = FrmOperationManualOperator.objLanguage;
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var grid = sender as DataGridView;
            var rowIdx = (e.RowIndex + 1).ToString();

            var centerFormat = new StringFormat()
            {
                // right alignment might actually make more sense for numbers
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);

        }

        private void FrmMasterMaintenanceDetail_Load(object sender, EventArgs e)
        {
            string strMasterMaintenance = "Master Maintenance";
            string strAutoAdjustment = "Auto adjustment";
            string strAddLine = "Add line";
            string strDelLine = "Del line";
            string strCopyLine = "Copy line";
            string strCutLine = "Cut line";
            string strPasteLine = "Paste line";
            //string strViewer = "Viewer";
            string strViewer = "Preview";
            string strSaveAs = "Save as";
            string strSave = "Save";
            string strCancel = "Cancel";


            lblMasterMaintenance.Text = objLanguage.Translate(strMasterMaintenance);
            btnAutoAdjustment.Text = objLanguage.Translate(strAutoAdjustment);
            btnAddLine.Text = objLanguage.Translate(strAddLine);
            btnDelLine.Text = objLanguage.Translate(strDelLine);
            btnCopyLine.Text = objLanguage.Translate(strCopyLine);
            btnCutLine.Text = objLanguage.Translate(strCutLine);
            btnPasteLine.Text = objLanguage.Translate(strPasteLine);
            btnViewer.Text = objLanguage.Translate(strViewer);
            btnSaveAs.Text = objLanguage.Translate(strSaveAs);
            btnSave.Text = objLanguage.Translate(strSave);
            btnCancel.Text = objLanguage.Translate(strCancel);

            dataGridView1.Columns[0].HeaderText = objLanguage.Translate("PIC Main1");
            dataGridView1.Columns[1].HeaderText = objLanguage.Translate("PIC Main2");
            dataGridView1.Columns[2].HeaderText = objLanguage.Translate("PIC Sub");
            dataGridView1.Columns[3].HeaderText = objLanguage.Translate("Comment");
            dataGridView1.Columns[4].HeaderText = objLanguage.Translate("Title");
            dataGridView1.Columns[5].HeaderText = objLanguage.Translate("Message");
            dataGridView1.Columns[6].HeaderText = objLanguage.Translate("Manual");
            dataGridView1.Columns[7].HeaderText = objLanguage.Translate("Input Conditions");
            dataGridView1.Columns[8].HeaderText = objLanguage.Translate("Input Comment");
            dataGridView1.Columns[9].HeaderText = objLanguage.Translate("Input Value1");
            dataGridView1.Columns[10].HeaderText = objLanguage.Translate("Input Value2");
            dataGridView1.Columns[11].HeaderText = objLanguage.Translate("Unit");

            dataGridView1.RowTemplate.Height = 50;

            FrmOperationManualOperator.isViewer = false;

            List<string> tmp = null;
            Master = new List<List<string>>();
            tmp = null;
            Int32 i = 0;
            Int32 j = 0;
            using (var csv = new CsvReader(csvPartFile))
            {
                while ((tmp = csv.ReadRow()) != null)
                {
                    //if (j == 0)
                    //{
                    //    FrmOperationManualOperator.excelPathShare = tmp[0];
                    //    j = j + 1;
                    //    i = 0;
                    //    continue;
                    //}

                    Master.Add(tmp);

                    if (tmp.Count >= 14)
                    {
                        //dataGridView1.ColumnCount = 3;
                        //dataGridView1.Columns[0].Name = "Product ID";
                        //dataGridView1.Columns[1].Name = "Product Name";
                        //dataGridView1.Columns[2].Name = "Product Price";
                        //string[] row = new string[] { null , null, null, this.Master[i][0], this.Master[i][1], this.Master[i][2],
                        //this.Master[i][3], this.Master[i][4], this.Master[i][5], this.Master[i][6],
                        //this.Master[i][7], this.Master[i][8], this.Master[i][9], this.Master[i][10],
                        //this.Master[i][11], "C:\\TOMAS TECH\\Shodensha (Thailand)\\File\\Sample_02.xlsx" ,  this.Master[i][13] };

                        string[] row = new string[] { null , null, null, this.Master[i][0], this.Master[i][1], this.Master[i][2],
                        this.Master[i][3], this.Master[i][4], this.Master[i][5], this.Master[i][6],
                        this.Master[i][7], this.Master[i][8], this.Master[i][9], this.Master[i][10],
                        this.Master[i][11], this.Master[0][12] ,  this.Master[i][13] };

                        dataGridView1.Rows.Add(row);

                        FrmOperationManualOperator.excelPathShare = this.Master[0][12];

                        if (dataGridView1[14, i].Value != null)
                        {
                            if (dataGridView1[14, i].Value != string.Empty)
                            {
                                dataGridView1[2, i].Value = null;
                                byte[] data;
                                //using (MemoryStream ms = new MemoryStream())
                                //{
                                data = Convert.FromBase64String(dataGridView1[14, i].Value.ToString());

                                //Image.GetThumbnailImageAbort myCallback1 =
                                //        new Image.GetThumbnailImageAbort(ThumbnailCallback);
                                Image image = byteArrayToImage((byte[])data);
                                ExifRotate(image);
                                //Image myThumbnail1 = image.GetThumbnailImage(80, 50,
                                //    myCallback1, IntPtr.Zero);

                                //dataGridView1[2, i].Value = myThumbnail1;
                                dataGridView1[2, i].Value = image;

                                //}

                            }
                        }

                        if (dataGridView1[12, i].Value != null)
                        {
                            if (dataGridView1[12, i].Value != string.Empty)
                            {
                                dataGridView1[0, i].Value = null;
                                byte[] data;
                                //using (MemoryStream ms = new MemoryStream())
                                //{
                                data = Convert.FromBase64String(dataGridView1[12, i].Value.ToString());

                                //Image.GetThumbnailImageAbort myCallback1 =
                                //        new Image.GetThumbnailImageAbort(ThumbnailCallback);
                                Image image = byteArrayToImage((byte[])data);
                                ExifRotate(image);
                                //Image myThumbnail1 = image.GetThumbnailImage(80, 50,
                                //    myCallback1, IntPtr.Zero);

                                //dataGridView1[0, i].Value = myThumbnail1;
                                dataGridView1[0, i].Value = image;

                                //}

                            }
                        }
                        
                        if (dataGridView1[13, i].Value != null)
                        {
                            if (dataGridView1[13, i].Value != string.Empty)
                            {
                                dataGridView1[1, i].Value = null;
                                byte[] data;
                                //using (MemoryStream ms = new MemoryStream())
                                //{
                                data = Convert.FromBase64String(dataGridView1[13, i].Value.ToString());

                                //Image.GetThumbnailImageAbort myCallback1 =
                                //        new Image.GetThumbnailImageAbort(ThumbnailCallback);
                                Image image = byteArrayToImage((byte[])data);
                                ExifRotate(image);
                                //Image myThumbnail1 = image.GetThumbnailImage(80, 50,
                                //    myCallback1, IntPtr.Zero);

                                //dataGridView1[1, i].Value = myThumbnail1;
                                dataGridView1[1, i].Value = image;

                                //}

                            }
                        }



                    }

                    i++;

                }
                csv.Close();

            }//using end

            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.ShowCellToolTips = false;
            dataGridView1.AllowUserToOrderColumns = false;

        }

        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 btnAutoAdjustment_Click(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAddLine_Click(object sender, EventArgs e)
        {
            Int32 intRow = dataGridView1.RowCount;
            dataGridView1.Rows.Add();
            dataGridView1[15, intRow].Value = FrmOperationManualOperator.excelPathShare;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        public bool ThumbnailCallback()
        {
            return false;
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            string strPictureText = string.Empty;
            if ((e.ColumnIndex == 0 || e.ColumnIndex == 1) && (e.RowIndex != -1))
            {
                if ((dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 12]).Value == null)
                {
                    strPictureText = string.Empty;
                }
                else
                {
                    strPictureText = (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 12]).Value.ToString();
                }

                FrmMasterMaintenanceImage frmMasterMaintenanceImage = new FrmMasterMaintenanceImage(strPictureText);

                //this.Dispose();

                frmMasterMaintenanceImage.ShowDialog();

                try
                {
                    if (picturePartFile != string.Empty)
                    {
                        PictureBox imageControl = new PictureBox();
                        //imageControl.Height = 640;
                        //imageControl.Width = 840;

                        Image.GetThumbnailImageAbort myCallback =
                                new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        Bitmap myBitmap = new Bitmap(picturePartFile);


                        int sourceWidth = myBitmap.Width;
                        int sourceHeight = myBitmap.Height;
                        Image myThumbnail = myBitmap.GetThumbnailImage(sourceWidth, sourceHeight,
                            myCallback, IntPtr.Zero);

                        imageControl.Height = sourceHeight;
                        imageControl.Width = sourceWidth;
                        //imageControl.Image = myThumbnail;
                        imageControl.Image = myBitmap;

                        //Image myThumbnail = myBitmap.GetThumbnailImage(840, 640,
                        //    myCallback, IntPtr.Zero);

                        //imageControl.Image = myThumbnail;

                        //Image myImage = myThumbnail;
                        Image myImage = myBitmap;
                        ExifRotate(myImage);
                        byte[] data;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            data = ms.ToArray();
                            string s3 = Convert.ToBase64String(data);
                            data = Convert.FromBase64String(s3);

                            (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 12]).Value = s3;

                            ms.Close();
                            ms.Dispose();

                            //PictureBox imageControl1 = new PictureBox();
                            //imageControl1.Height = 50;
                            //imageControl1.Width = 80;

                            //Image.GetThumbnailImageAbort myCallback1 =
                            //        new Image.GetThumbnailImageAbort(ThumbnailCallback);
                            Bitmap myBitmap1 = new Bitmap(picturePartFile);
                            ExifRotate(myBitmap1);
                            //Image myThumbnail1 = myBitmap1.GetThumbnailImage(80, 50,
                            //    myCallback1, IntPtr.Zero);
                            //imageControl1.Image = myThumbnail1;

                            (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value = myBitmap1;

                        }
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }



            }


            if (e.ColumnIndex == 2)
            {
                if ((dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 12]).Value == null)
                {
                    strPictureText = string.Empty;
                }
                else
                {
                    strPictureText = (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 12]).Value.ToString();
                }

                FrmMasterMaintenanceImage frmMasterMaintenanceImage = new FrmMasterMaintenanceImage(strPictureText);

                //this.Dispose();

                frmMasterMaintenanceImage.ShowDialog();

                try
                {
                    if (picturePartFile != string.Empty)
                    {

                        PictureBox imageControl = new PictureBox();
                        //imageControl.Height = 272;
                        //imageControl.Width = 358;

                        Image.GetThumbnailImageAbort myCallback =
                                new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        Bitmap myBitmap = new Bitmap(picturePartFile);
                        //Image myThumbnail = myBitmap.GetThumbnailImage(358, 272,
                        //    myCallback, IntPtr.Zero);
                        //imageControl.Image = myThumbnail;

                        int sourceWidth = myBitmap.Width;
                        int sourceHeight = myBitmap.Height;
                        Image myThumbnail = myBitmap.GetThumbnailImage(sourceWidth, sourceHeight,
                            myCallback, IntPtr.Zero);

                        imageControl.Height = sourceHeight;
                        imageControl.Width = sourceWidth;
                        //imageControl.Image = myThumbnail;
                        imageControl.Image = myBitmap;

                        Image myImage = myThumbnail;
                        ExifRotate(myImage);
                        byte[] data;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                            data = ms.ToArray();
                            string s3 = Convert.ToBase64String(data);
                            data = Convert.FromBase64String(s3);

                            (dataGridView1.Rows[e.RowIndex].Cells[14]).Value = s3;

                            ms.Close();
                            ms.Dispose();
                        }

                        //PictureBox imageControl1 = new PictureBox();
                        //imageControl1.Height = 50;
                        //imageControl1.Width = 80;

                        //Image.GetThumbnailImageAbort myCallback1 =
                        //        new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        Bitmap myBitmap1 = new Bitmap(picturePartFile);
                        ExifRotate(myBitmap1);
                        //Image myThumbnail1 = myBitmap1.GetThumbnailImage(80, 50,
                        //    myCallback1, IntPtr.Zero);
                        //imageControl1.Image = myThumbnail1;

                        (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value = myBitmap1;
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }

            }


            if (e.ColumnIndex == 7)
            {
                if ((dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value == null)
                {
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value = string.Empty;
                }
                FrmCondition frmCondition = new FrmCondition((dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value.ToString());
                frmCondition.ShowDialog();

                if (isCancel == false)
                {
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).Value = conditionForSave;
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 1]).Value = inputComment;
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 2]).Value = inputValue1;
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 3]).Value = inputValue2;
                    (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex + 4]).Value = strUnit;
                }

            }

        }

        private const int exifOrientationID = 0x112; //274

        public static void ExifRotate(Image img)
        {
            if (!img.PropertyIdList.Contains(exifOrientationID))
                return;

            var prop = img.GetPropertyItem(exifOrientationID);
            int val = BitConverter.ToUInt16(prop.Value, 0);
            var rot = RotateFlipType.RotateNoneFlipNone;

            if (val == 3 || val == 4)
                rot = RotateFlipType.Rotate180FlipNone;
            else if (val == 5 || val == 6)
                rot = RotateFlipType.Rotate90FlipNone;
            else if (val == 7 || val == 8)
                rot = RotateFlipType.Rotate270FlipNone;

            if (val == 2 || val == 4 || val == 5 || val == 7)
                rot |= RotateFlipType.RotateNoneFlipX;

            if (rot != RotateFlipType.RotateNoneFlipNone)
            {
                img.RotateFlip(rot);
                img.RemovePropertyItem(exifOrientationID);
            }
        }

        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 btnDelLine_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow != null)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);

            }
        }

        private void btnCopyLine_Click(object sender, EventArgs e)
        {
            CopyToClipboard();
        }


        private void CopyToClipboard()
        {
            //Show Error if no row is selected
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Copy line"),
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Copy to clipboard
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
        }

        private void PasteClipboardValue()
        {
            //Show Error if no row is selected
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Paste line"),
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Get the starting Cell
            DataGridViewCell startCell = GetStartCell(dataGridView1);
            //Get the clipboard value in a dictionary
            Dictionary<int, Dictionary<int, string>> cbValue =
                    ClipBoardValues(Clipboard.GetText());

            int iRowIndex = startCell.RowIndex;
            foreach (int rowKey in cbValue.Keys)
            {
                int iColIndex = startCell.ColumnIndex;
                foreach (int cellKey in cbValue[rowKey].Keys)
                {
                    if ((cellKey == 0) || (cellKey == 1) || (cellKey == 2) || (cellKey == 3))
                    {
                        continue;
                    }

                    //Check if the index is within the limit
                    if (iColIndex <= dataGridView1.Columns.Count - 1
                    && iRowIndex <= dataGridView1.Rows.Count - 1)
                    {
                        DataGridViewCell cell = dataGridView1[iColIndex + 3, iRowIndex];

                        //Copy to selected cells if 'chkPasteToSelectedCells' is checked
                        //if ((chkPasteToSelectedCells.Checked && cell.Selected) ||
                        //    (!chkPasteToSelectedCells.Checked))

                        cell.Value = cbValue[rowKey][cellKey];
                    }
                    iColIndex++;
                }


                if (dataGridView1[14, iRowIndex].Value != null)
                {
                    if (dataGridView1[14, iRowIndex].Value != string.Empty)
                    {

                        byte[] data;
                        //using (MemoryStream ms = new MemoryStream())
                        //{
                        data = Convert.FromBase64String(dataGridView1[14, iRowIndex].Value.ToString());
                        //picMain3.Image = byteArrayToImage((byte[])data);

                        Image image = byteArrayToImage((byte[])data);
                        ExifRotate(image);

                        //Image.GetThumbnailImageAbort myCallback =
                        //    new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        //Bitmap myBitmap = new Bitmap(picturePartFile);
                        //Image myThumbnail = byteArrayToImage((byte[])data).GetThumbnailImage(80, 50,
                        //    myCallback, IntPtr.Zero);
                        //imageControl.Image = myThumbnail;

                        dataGridView1[2, iRowIndex].Value = image;

                        //}

                    }
                }

                if (dataGridView1[12, iRowIndex].Value != null)
                {
                    if (dataGridView1[12, iRowIndex].Value != string.Empty)
                    {

                        byte[] data;
                        //using (MemoryStream ms = new MemoryStream())
                        //{
                        data = Convert.FromBase64String(dataGridView1[12, iRowIndex].Value.ToString());
                        //picMain3.Image = byteArrayToImage((byte[])data);

                        Image image = byteArrayToImage((byte[])data);
                        ExifRotate(image);

                        //Image.GetThumbnailImageAbort myCallback =
                        //    new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        //Bitmap myBitmap = new Bitmap(picturePartFile);
                        //Image myThumbnail = byteArrayToImage((byte[])data).GetThumbnailImage(80, 50,
                        //    myCallback, IntPtr.Zero);
                        //imageControl.Image = myThumbnail;

                        dataGridView1[0, iRowIndex].Value = image;

                        //}

                    }
                }

                if (dataGridView1[13, iRowIndex].Value != null)
                {
                    if (dataGridView1[13, iRowIndex].Value != string.Empty)
                    {

                        byte[] data;
                        //using (MemoryStream ms = new MemoryStream())
                        //{
                        data = Convert.FromBase64String(dataGridView1[13, iRowIndex].Value.ToString());
                        //picMain3.Image = byteArrayToImage((byte[])data);

                        Image image = byteArrayToImage((byte[])data);
                        ExifRotate(image);

                        //Image.GetThumbnailImageAbort myCallback =
                        //    new Image.GetThumbnailImageAbort(ThumbnailCallback);
                        //Bitmap myBitmap = new Bitmap(picturePartFile);
                        //Image myThumbnail = byteArrayToImage((byte[])data).GetThumbnailImage(80, 50,
                        //    myCallback, IntPtr.Zero);
                        //imageControl.Image = myThumbnail;

                        dataGridView1[1, iRowIndex].Value = image;

                        //}

                    }
                }


                iRowIndex++;
            }
        }

        private void PasteClipboardValueSaveAs(string pathFile)
        {

            //Get the clipboard value in a dictionary
            Dictionary<int, Dictionary<int, string>> cbValue =
                    ClipBoardValues(Clipboard.GetText());

            //CSV Encoding
            System.Text.Encoding enc =
                System.Text.Encoding.UTF8;

            System.IO.StreamWriter sr =
                new System.IO.StreamWriter(pathFile, false, enc);

            string dataSaveAs = string.Empty;
            foreach (int rowKey in cbValue.Keys)
            {
                dataSaveAs = string.Empty;
                foreach (int cellKey in cbValue[rowKey].Keys)
                {
                    if ((cellKey == 0) || (cellKey == 1) || (cellKey == 2) || (cellKey == 3))
                    {
                        continue;
                    }

                    if (cellKey == 4)
                    {
                        dataSaveAs = cbValue[rowKey][cellKey].Replace(",", "");
                    }
                    else
                    {
                        dataSaveAs = dataSaveAs + "," + cbValue[rowKey][cellKey].Replace(",", "");
                    }

                    //if (cellKey == cbValue[rowKey].Keys.Count -1)
                    //{
                    //    if (rowKey == 0)
                    //    {
                    //        dataSaveAs = dataSaveAs + "," + "1";
                    //    }
                    //    else
                    //    {
                    //        dataSaveAs = dataSaveAs + "," + "0";
                    //    }

                    //}


                }

                if (rowKey == 0)
                {
                    dataSaveAs = dataSaveAs.Replace("\n", "").Replace("\r", "") + "," + "1";
                }
                else
                {
                    dataSaveAs = dataSaveAs.Replace("\n", "").Replace("\r", "") + "," + "0";
                }

                sr.WriteLine(dataSaveAs);

            }

            sr.Close();

            string pathFile000 = pathFile.Substring(0, (pathFile.Length - 3)) + "000";

            if (File.Exists(pathFile000))
            {
                File.Delete(pathFile000);
            }

            File.Copy(pathFile, pathFile000);

        }

        private DataGridViewCell GetStartCell(DataGridView dgView)
        {
            //get the smallest row,column index
            if (dgView.SelectedCells.Count == 0)
                return null;

            int rowIndex = dgView.Rows.Count - 1;
            int colIndex = dgView.Columns.Count - 1;

            foreach (DataGridViewCell dgvCell in dgView.SelectedCells)
            {
                if (dgvCell.RowIndex < rowIndex)
                    rowIndex = dgvCell.RowIndex;
                if (dgvCell.ColumnIndex < colIndex)
                    colIndex = dgvCell.ColumnIndex;
            }

            return dgView[colIndex, rowIndex];
        }

        private Dictionary<int, Dictionary<int, string>> ClipBoardValues(string clipboardValue)
        {
            Dictionary<int, Dictionary<int, string>>
            copyValues = new Dictionary<int, Dictionary<int, string>>();

            String[] lines = clipboardValue.Split('\n');

            for (int i = 0; i <= lines.Length - 1; i++)
            {
                copyValues[i] = new Dictionary<int, string>();
                String[] lineContent = lines[i].Split('\t');

                //if an empty cell value copied, then set the dictionary with an empty string
                //else Set value to dictionary
                if (lineContent.Length == 0)
                    copyValues[i][0] = string.Empty;
                else
                {
                    for (int j = 0; j <= lineContent.Length - 1; j++)
                        copyValues[i][j] = lineContent[j];
                }
            }
            return copyValues;
        }

        private void btnPasteLine_Click(object sender, EventArgs e)
        {
            //Perform paste Operation
            PasteClipboardValue();
        }

        private void btnCutLine_Click(object sender, EventArgs e)
        {
            //Show Error if no row is selected
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Cut line"),
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Copy to clipboard
            CopyToClipboard();

            //Clear selected cells
            foreach (DataGridViewCell dgvCell in dataGridView1.SelectedCells)
                switch (dgvCell.OwningColumn.CellType.Name)
                {
                    case "DataGridViewTextBoxCell":
                        dgvCell.Value = string.Empty;
                        break;
                    case "DataGridViewCheckBoxCell":
                        dgvCell.Value = false;
                        break;
                    case "DataGridViewImageCell":
                        dgvCell.Value = null;
                        break;
                    default:
                        break;
                }

            if (dataGridView1.CurrentRow != null)
            {
                dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);

            }

        }

        private void FrmMasterMaintenanceDetail_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void FrmMasterMaintenanceDetail_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {

        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
            {
                btnPasteLine_Click(sender, e);
            }
            if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control)
            {
                btnCopyLine_Click(sender, e);
            }
            if (e.KeyCode == Keys.X && e.Modifiers == Keys.Control)
            {
                btnCutLine_Click(sender, e);
            }
            if ((e.KeyCode == Keys.Delete) && ((dataGridView1.CurrentCell.ColumnIndex == 0) || (dataGridView1.CurrentCell.ColumnIndex == 1)
                    || (dataGridView1.CurrentCell.ColumnIndex == 2)))
            {
                //dataGridView1.CurrentCell.Value = string.Empty;
                dataGridView1.CurrentCell.Value = null;
                Int32 iRowIndex = dataGridView1.CurrentCell.RowIndex;
                dataGridView1[dataGridView1.CurrentCell.ColumnIndex + 12, iRowIndex].Value = string.Empty;
            }


        }

        private void btnViewer_Click(object sender, EventArgs e)
        {
            //if (dataGridView1.SelectedRows.Count == 0)
            if ((dataGridView1.CurrentRow.Index == null) && (dataGridView1.CurrentCell.RowIndex == null))
            {
                //MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Viewer"),
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Preview"),
            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            FrmOperationManualOperator.strPage = "";

            FrmOperationManualOperator.isViewer = true;

            FrmOperationManual frmOperationManual = new FrmOperationManual(true, dataGridView1, csvPartFile, "Inspection Work", loginUser);
            frmOperationManual.ShowDialog();

            FrmOperationManualOperator.isViewer = false;

            //FrmInspectionWork frmInspectionWork = new FrmInspectionWork(true, dataGridView1);
            //frmInspectionWork.ShowDialog();
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            dataGridView1.SelectAll();

            //Show Error if no row is selected
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Save as"),
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = objLanguage.Translate("Master file") + " (*.003)|*.003";
            //saveFileDialog1.Filter = "Working (*.000)|*.000|Completion (*.001)|*.001|Error (*.002)|*.002|Master file (*.003)|*.003";

            saveFileDialog1.FileName = csvPartFile.Substring(0, csvPartFile.Length - 3) + "003";

            DialogResult result = saveFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {

                CopyToClipboard();

                csvPartFileSaveAs = saveFileDialog1.FileName;

                PasteClipboardValueSaveAs(csvPartFileSaveAs);


                MessageBox.Show(this, objLanguage.Translate("Save as is Complete."),
                                       objLanguage.Translate("Information"), MessageBoxButtons.OK,
                                       MessageBoxIcon.Information,
                                       MessageBoxDefaultButton.Button1, 0);

            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            //Show Error if no row is selected

            dataGridView1.SelectAll();

            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(objLanguage.Translate("Please select a row"), objLanguage.Translate("Save"),
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            CopyToClipboard();

            PasteClipboardValueSaveAs(csvPartFile);

            MessageBox.Show(this, objLanguage.Translate("Save is Complete."),
                                   objLanguage.Translate("Information"), MessageBoxButtons.OK,
                                   MessageBoxIcon.Information,
                                   MessageBoxDefaultButton.Button1, 0);
        }

        private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {

        }

        void Control_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == ',')
            {
                e.Handled = true;
            }
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is TextBox)
            {
                e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress);
            }
        }

        private void FrmMasterMaintenanceDetail_KeyPress(object sender, KeyPressEventArgs e)
        {

        }
    }
}
