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 static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Net;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using SixLabors.ImageSharp.Drawing;
using System.Drawing.Text;
using PackingControlSystem.lib;

namespace PackingControlSystem
{
    public partial class frmUser : Form
    {
        private List<List<string>> Settings = new List<List<string>>();
        DataTable dtUser = new DataTable();
        DataTable dtUserSelect = new DataTable();
        private string userID = string.Empty;
        private string userName = string.Empty;

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

        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 frmUser_Load(object sender, EventArgs e)
        {
            List<string> tmp = null;
            dgvUser.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();

            SetPermission();

            SettxtReadOnly();
        }

        private void SetPermission()
        {
            cbbPermission.Items.Clear();

            cbbPermission.Items.Add("ADMINISTRATOR");
            cbbPermission.Items.Add("LEADER");
            cbbPermission.Items.Add("QA");
            cbbPermission.Items.Add("OPERATOR");

            //cbbPermission.SelectedItem = ("USER");
        }

        private void SettxtReadOnly()
        {
            txtUsername.ReadOnly = true;
            txtPassword.ReadOnly = true;
            txtName.ReadOnly = true;
            txtUsername.BackColor = SystemColors.Control;
            txtPassword.BackColor = SystemColors.Control;
            txtName.BackColor = SystemColors.Control;
            cbbPermission.Enabled = false;
            cbxStatus.Enabled = false;
            btnSave.Enabled = false;
            btnClear.Enabled = false;
            btnAdd.Enabled = true;
        }

        private void SettxtStart()
        {
            txtUsername.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtName.Text = string.Empty;
            cbxStatus.Checked = false;
            pbUser.Image = null;
            btnDelete.Enabled = true;

        }

        private void loadTable()
        {
            dtUser = new DataTable();
            clsUtil_MSSQL.GetDataFromTBUser(RtnDbCon(), "TM_USER", ref dtUser);
            dgvUser.DataSource = dtUser;
            //dgvPart.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            dgvUser.RowHeadersWidth = 70;

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

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

                }
                else
                {


                }

            }

        }

        private void dgvUser_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 = dgvUser.Rows[idx];
            row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }

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

        private void SettxtWrite()
        {
            txtUsername.ReadOnly = false;
            txtPassword.ReadOnly = false;
            txtName.ReadOnly = false;
            txtUsername.BackColor = SystemColors.Window;
            txtPassword.BackColor = SystemColors.Window;
            txtName.BackColor = SystemColors.Window;
            cbbPermission.Enabled = true;
            cbxStatus.Enabled = true;
            btnAdd.Enabled = false;
            btnSave.Enabled = true;
            btnClear.Enabled = true;
            //btnDelete.Enabled = false;
        }

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

            if (userID != string.Empty)
            {
                clsUtil_MSSQL.updateUser(RtnDbCon(), userID, txtName.Text, txtPassword.Text, cbbPermission.Text,
                    cbxStatus.Checked, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"));

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

                loadTable();

                SettxtReadOnly();
                SettxtStart();
                SetPermission();
                userID = string.Empty;

            }

            else if (userID == string.Empty)
            {

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

                clsUtil_MSSQL.insertUser(RtnDbCon(), txtUsername.Text, txtName.Text, txtPassword.Text, cbbPermission.Text,
                    cbxStatus.Checked, DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"), DateTime.Now.ToString("yyyyMMdd"),
                    DateTime.Now.ToString("HHmmss"));

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

                loadTable();

                SettxtReadOnly();
                SettxtStart();
                SetPermission();
                userID = string.Empty;

            }
        }

        private void dgvUser_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {



        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            SettxtReadOnly();
            SettxtStart();
            SetPermission();
            userID = string.Empty;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            if (txtUsername.Text == string.Empty)
            {
                MessageBox.Show(this, "กรุณาเลือกรายการที่จะลบก่อน",
                                       "Operator Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

            if (userName == txtUsername.Text)
            {
                MessageBox.Show(this, "ไม่สามารถลบผู้ใช้งานที่กำลัง Login อยู่ขณะนี้ได้",
                                       "Operator Information", MessageBoxButtons.OK,
                                       MessageBoxIcon.Warning,
                                       MessageBoxDefaultButton.Button1, 0);
                return;
            }

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

            if (dialogResult == DialogResult.Yes)
            {
                if (userID != string.Empty)
                {
                    clsUtil_MSSQL.deleteUser(RtnDbCon(), userID);

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

                    loadTable();

                    SettxtReadOnly();
                    SettxtStart();
                    SetPermission();
                    userID = string.Empty;
                }
                else if (dialogResult == DialogResult.No)
                {
                    return;
                }



            }
        }

        private void dgvUser_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

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

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

            dtUserSelect = new DataTable();
            int rowindex = dgvUser.CurrentRow.Index;
            clsUtil_MSSQL.GetDataFromTBUserSelectAll(RtnDbCon(), "TM_USER", ref dtUserSelect, dgvUser[0, rowindex].Value.ToString());
            userID = dgvUser[0, rowindex].Value.ToString();
            txtUsername.Text = dtUserSelect.Rows[0][1].ToString();
            txtPassword.Text = dtUserSelect.Rows[0][3].ToString();
            txtName.Text = dtUserSelect.Rows[0][2].ToString();
            cbbPermission.Text = dtUserSelect.Rows[0][4].ToString();
            if ((dtUserSelect.Rows[0][5].ToString() == "1") || (dtUserSelect.Rows[0][5].ToString() == "Y"))
            {
                cbxStatus.Checked = true;
            }
            //else if (dtUserSelect.Rows[0][5].ToString() == "0")
            else
            {
                cbxStatus.Checked = false;
            }

            //string strUsername = string.Empty;
            //string strPassword = string.Empty;
            //strUsername = txtUsername.Text.ToUpper();
            //strPassword = txtPassword.Text.ToUpper();
            //string barcode = strUsername + "%" + strPassword;
            string barcode = txtUsername.Text + "%" + txtPassword.Text;

            int lenbarcode = 0;
            if (barcode.Length < 20)
            {
                lenbarcode = 20;
            }
            else
            {
                lenbarcode = barcode.Length;
            }

            //Bitmap bitm = new Bitmap(barcode.Length * 45, 160);
            //Bitmap bitm = new Bitmap(lenbarcode * 45, 250);
            Bitmap bitm = new Bitmap(lenbarcode * 45, 250);
            using (Graphics graphic = Graphics.FromImage(bitm))
            {

                //Font newfont = new Font("IDAutomationHC39M", 20);
                Font newfont = new Font("IDAutomationC39M", 30);
                PointF point = new PointF(40f, 60f);
                SolidBrush black = new SolidBrush(Color.Black);
                SolidBrush white = new SolidBrush(Color.White);
                graphic.FillRectangle(white, 0, 0, bitm.Width, bitm.Height);
                graphic.DrawString("*" + barcode + "*", newfont, black, point);

            }

            using (MemoryStream Mmst = new MemoryStream())
            {

                bitm.Save("ms", ImageFormat.Jpeg);
                pbUser.Image = bitm;
                pbUser.Width = bitm.Width;
                pbUser.Height = bitm.Height;

            }
        }



        private void btnExportBarcode_Click(object sender, EventArgs e)
        {
            //pbUser.Image.Save(Application.StartupPath + "\\Image\\picture1.jpg");
            SaveFileDialog sfd = new SaveFileDialog();
            //sfd.Filter = "Images|*.png;*.bmp;*.jpg";
            sfd.Filter = "JPeg Image|*.jpg";
            ImageFormat format = ImageFormat.Png;
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string ext = System.IO.Path.GetExtension(sfd.FileName);
                switch (ext)
                {
                    case ".jpg":
                        format = ImageFormat.Jpeg;
                        break;
                        //case ".bmp":
                        //    format = ImageFormat.Bmp;
                        //    break;
                }
                pbUser.Image.Save(sfd.FileName, format);
            }
        }
    }
}
