using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using TinyHeels.App_Code;

namespace TinyHeels
{
    public partial class controlStock : UserControl
    {
        private static controlStock _instance;
        public static controlStock Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new controlStock();
                }
                return _instance;
            }
        }
        public controlStock()
        {
            InitializeComponent();
            try
            {
                cboColor.SelectedIndex = 0;
                loadCategory();
                cboCategory.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox("Error Loading Data");
                error.ShowDialog();
            }
        }
        public void loadCategory()
        {
            try
            {
                Dictionary<string, string> test = new Dictionary<string, string>();
                Category cat = new Category();
                DataTable dt = cat.getAllCategories();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    test.Add(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString());
                }
                cboCategory.DataSource = new BindingSource(test, null);
                cboCategory.DisplayMember = "Value";
                cboCategory.ValueMember = "key";
                cboCategory.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void textBox1_DoubleClick(object sender, System.EventArgs e)
        {
            try
            {
                generateCode();
            }
            catch (Exception ex)
            {
                ErrorBox error = new ErrorBox(ex.Message);
                error.ShowDialog();
            }
        }
        string bcode = "";
        public void generateCode()
        {
            try
            {
                txtCode.Text = "";
                DateTime dt = new DateTime(DateTime.Now.Year, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
                DateTime dtNow = DateTime.Now;
                TimeSpan result = dtNow.Subtract(dt);
                int seconds = Convert.ToInt32(result.TotalSeconds);
                bcode += seconds.ToString();
                int len = bcode.Length;
                if (len < 8)
                {
                    for (int i = len; i < 8; i++)
                    {
                        bcode = "0" + bcode;
                    }
                }
                bcode = DateTime.Now.ToString("yy") + "CTG" + bcode;
                txtCode.Text = bcode;
                bcode = "";
            }
            catch (Exception ex)
            {

                throw new Exception("Sorry Could Not Generate Code");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string code = (string.IsNullOrWhiteSpace(txtCode.Text)) ? "-" : txtCode.Text;
                string article = (string.IsNullOrWhiteSpace(txtArticle.Text)) ? "-" : txtArticle.Text;
                string color = cboColor.Text;
                string size = (string.IsNullOrWhiteSpace(txtSize.Text)) ? "-" : txtSize.Text;
                int category = Int32.Parse(((KeyValuePair<string, string>)cboCategory.SelectedItem).Key);
                double cost = double.Parse((string.IsNullOrWhiteSpace(txtCost.Text) ? "0.0" : txtCost.Text));
                double price = double.Parse((string.IsNullOrWhiteSpace(txtPrice.Text) ? "0.0" : txtPrice.Text));
                double quantity = double.Parse(string.IsNullOrWhiteSpace(txtQuantity.Text) ? "0.0" : txtQuantity.Text);

                bool onSale = false;
                if (chkOnSale.Checked)
                {
                    onSale = true;
                }
                else
                {
                    onSale = false;
                }
                bool onUpdate = false;
                if (chkOnUpdate.Checked)
                    onUpdate = true;
                else
                    onUpdate = false;

                if (code.Equals("-") || code.Length < 7 || article.Length < 1 || cost > price)
                {
                    ErrorBox error = new ErrorBox("Sorry You Have Filled Invalid Data");
                    error.ShowDialog();
                }
                else
                {
                    Products prd = new Products();
                    prd.code = code;
                    prd.article = article;
                    prd.color = color;
                    prd.size = size;
                    prd.category = category;
                    prd.quantity = quantity;
                    prd.cost = cost;
                    prd.price = price;
                    prd.onSale = onSale;
                    prd.onUpdate = onUpdate;
                    if (prd.checkProductAvailability())
                    {
                        prd.updateProduct();
                    }
                    else
                    {
                        prd.insertNewProduct();
                    }
                    resetData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void chkOnSale_CheckedChanged(object sender, EventArgs e)
        {
            if (chkOnSale.Checked)
                chkOnSale.Text = "Yes";
            else
                chkOnSale.Text = "No";
        }

        private void chkOnUpdate_CheckedChanged(object sender, EventArgs e)
        {
            if (chkOnUpdate.Checked)
            {
                chkOnUpdate.Text = "Yes";
            }
            else
            {
                chkOnUpdate.Text = "No";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            ManageCategory obj = new ManageCategory();
            obj.ShowDialog();
            cboCategory.DataSource = null;
            loadCategory();
        }

        public void resetData()
        {
            try
            {
                txtCode.Text = "";
                txtArticle.Text = "";
                txtCodeSearch.Text = "";
                txtCost.Text = "";
                txtPrice.Text = "";
                txtQuantity.Text = "";
                txtSize.Text = "";
                cboCategory.SelectedIndex = 0;

                chkOnSale.Checked = false;
                chkOnUpdate.Checked = false;
            }
            catch (Exception ex)
            {

            }
        }

        private void txtCodeSearch_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                string str = txtCodeSearch.Text;
                Products prd = new Products();
                DataTable dt = prd.searchByCodeArticle(str);
                productGrid.DataSource = dt;
            }
            catch (Exception ex)
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            resetData();
        }

        private void productGrid_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string code = productGrid.SelectedRows[0].Cells[0].Value.ToString();
                Products prd = new Products();
                prd.code = code;
                DataTable dt = prd.getByCode();
                txtCode.Text = dt.Rows[0][0].ToString();
                txtArticle.Text = dt.Rows[0][1].ToString();
                string color = dt.Rows[0][2].ToString();
                int count = 0;
                foreach (string li in cboColor.Items)
                {
                    if (li == color)
                    {
                        cboColor.SelectedIndex = count;
                    }
                    count++;
                }
                txtSize.Text = dt.Rows[0][3].ToString();
                txtCost.Text = dt.Rows[0][4].ToString();
                txtPrice.Text = dt.Rows[0][5].ToString();
                txtQuantity.Text = dt.Rows[0][6].ToString();
                int category = Int32.Parse(dt.Rows[0][7].ToString());

                count = 0;
                for (int x = 0; x < cboCategory.Items.Count; x++)
                {
                    int str = Int32.Parse(((KeyValuePair<string, string>)cboCategory.Items[x]).Key);
                    if (str == category)
                    {
                        cboCategory.SelectedIndex = count;
                        break;
                    }
                    count++;
                }


                bool onSale = bool.Parse(dt.Rows[0][8].ToString());
                if (onSale)
                    chkOnSale.Checked = true;
                else
                    chkOnSale.Checked = false;
                bool onUpdate = bool.Parse(dt.Rows[0][9].ToString());
                if (onUpdate)
                    chkOnUpdate.Checked = true;
                else
                    chkOnUpdate.Checked = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void de(object sender, EventArgs e)
        {
            YesNo obj = new YesNo("Do you want to delete\nthe selected product?");
            obj.ShowDialog();
            if (Common.command == true)
            {
                try
                {

                    string productCode = productGrid.SelectedRows[0].Cells[0].Value.ToString();
                    Products p = new Products();
                    p.code = productCode;
                    p.deleteProduct();

                    productGrid.DataSource = null;
                    ErrorBox d = new ErrorBox("Done Deletion");
                    d.ShowDialog();

                    resetData();
                }
                catch (Exception ex)
                {
                    ErrorBox objx = new ErrorBox("Error: Could not delete.\nTry again.");
                    objx.ShowDialog();
                }
            }
            else
            {
                //----------------
            }
        }
        bool x = true;
        private void button5_Click(object sender, EventArgs e)
        {
            if (x)
            {
                Products prd = new Products();
                DataTable dt = prd.getAll();
                productGrid.DataSource = dt;
                x = false;
            }
            else
            {
                productGrid.DataSource = null;
                x = true;
            }
        }
    }
}

