using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using DataLibrary.DataObjects;

namespace UsingObjects
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class MainForm : System.Windows.Forms.Form
    {
        private C1.Data.C1DataSet c1DataSet1;
        private System.Windows.Forms.ListView viewProducts;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnNew;
        private System.Windows.Forms.Button btnDelete;
        private System.Windows.Forms.Button btnEdit;
        private System.Windows.Forms.Button btnCommit;
        private System.Windows.Forms.Button btnRefresh;
        private System.Windows.Forms.Button btnClose;
        private System.Windows.Forms.ColumnHeader columnHeader1;
        private System.Windows.Forms.ColumnHeader columnHeader2;
        private System.Windows.Forms.ImageList imageList1;
        private System.Windows.Forms.ColumnHeader columnHeader3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label labTotal;
        private System.ComponentModel.IContainer components;

        public MainForm()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm));
            this.c1DataSet1 = new C1.Data.C1DataSet();
            this.viewProducts = new System.Windows.Forms.ListView();
            this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
            this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
            this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
            this.imageList1 = new System.Windows.Forms.ImageList(this.components);
            this.label1 = new System.Windows.Forms.Label();
            this.btnNew = new System.Windows.Forms.Button();
            this.btnDelete = new System.Windows.Forms.Button();
            this.btnEdit = new System.Windows.Forms.Button();
            this.btnCommit = new System.Windows.Forms.Button();
            this.btnRefresh = new System.Windows.Forms.Button();
            this.btnClose = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.labTotal = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.c1DataSet1)).BeginInit();
            this.SuspendLayout();
            // 
            // c1DataSet1
            // 
            this.c1DataSet1.BindingContextCtrl = this;
            this.c1DataSet1.DataLibrary = "DataLibrary";
            this.c1DataSet1.DataLibraryUrl = "";
            this.c1DataSet1.DataSetDef = "DataSet1";
            this.c1DataSet1.Locale = new System.Globalization.CultureInfo("en-US");
            this.c1DataSet1.Name = "c1DataSet1";
            this.c1DataSet1.SchemaClassName = "DataLibrary.DataClass";
            this.c1DataSet1.SchemaDef = null;
            // 
            // viewProducts
            // 
            this.viewProducts.AllowColumnReorder = true;
            this.viewProducts.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.viewProducts.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
                                                                                           this.columnHeader1,
                                                                                           this.columnHeader2,
                                                                                           this.columnHeader3});
            this.viewProducts.FullRowSelect = true;
            this.viewProducts.GridLines = true;
            this.viewProducts.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
            this.viewProducts.HideSelection = false;
            this.viewProducts.Location = new System.Drawing.Point(12, 30);
            this.viewProducts.Name = "viewProducts";
            this.viewProducts.Size = new System.Drawing.Size(442, 244);
            this.viewProducts.SmallImageList = this.imageList1;
            this.viewProducts.Sorting = System.Windows.Forms.SortOrder.Ascending;
            this.viewProducts.TabIndex = 1;
            this.viewProducts.View = System.Windows.Forms.View.Details;
            this.viewProducts.KeyDown += new System.Windows.Forms.KeyEventHandler(this.viewProducts_KeyDown);
            this.viewProducts.DoubleClick += new System.EventHandler(this.viewProducts_DoubleClick);
            // 
            // columnHeader1
            // 
            this.columnHeader1.Text = "Product Name";
            this.columnHeader1.Width = 190;
            // 
            // columnHeader2
            // 
            this.columnHeader2.Text = "Supplier Company";
            this.columnHeader2.Width = 162;
            // 
            // columnHeader3
            // 
            this.columnHeader3.Text = "Country";
            this.columnHeader3.Width = 70;
            // 
            // imageList1
            // 
            this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
            this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
            this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
            this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
            // 
            // label1
            // 
            this.label1.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.label1.Location = new System.Drawing.Point(12, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(68, 19);
            this.label1.TabIndex = 0;
            this.label1.Text = "Products:";
            // 
            // btnNew
            // 
            this.btnNew.Location = new System.Drawing.Point(468, 32);
            this.btnNew.Name = "btnNew";
            this.btnNew.Size = new System.Drawing.Size(116, 23);
            this.btnNew.TabIndex = 6;
            this.btnNew.TabStop = false;
            this.btnNew.Text = "Ins - New Product";
            this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
            // 
            // btnDelete
            // 
            this.btnDelete.Location = new System.Drawing.Point(468, 62);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(116, 23);
            this.btnDelete.TabIndex = 7;
            this.btnDelete.TabStop = false;
            this.btnDelete.Text = "Del - Delete Rows";
            this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
            // 
            // btnEdit
            // 
            this.btnEdit.Location = new System.Drawing.Point(468, 94);
            this.btnEdit.Name = "btnEdit";
            this.btnEdit.Size = new System.Drawing.Size(116, 23);
            this.btnEdit.TabIndex = 8;
            this.btnEdit.TabStop = false;
            this.btnEdit.Text = "Enter - Edit Product";
            this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
            // 
            // btnCommit
            // 
            this.btnCommit.Location = new System.Drawing.Point(468, 218);
            this.btnCommit.Name = "btnCommit";
            this.btnCommit.Size = new System.Drawing.Size(116, 23);
            this.btnCommit.TabIndex = 9;
            this.btnCommit.TabStop = false;
            this.btnCommit.Text = "F2 - Commit";
            this.btnCommit.Click += new System.EventHandler(this.btnCommit_Click);
            // 
            // btnRefresh
            // 
            this.btnRefresh.Location = new System.Drawing.Point(468, 250);
            this.btnRefresh.Name = "btnRefresh";
            this.btnRefresh.Size = new System.Drawing.Size(116, 23);
            this.btnRefresh.TabIndex = 10;
            this.btnRefresh.TabStop = false;
            this.btnRefresh.Text = "F3 - Refresh";
            this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
            // 
            // btnClose
            // 
            this.btnClose.Location = new System.Drawing.Point(508, 299);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(76, 23);
            this.btnClose.TabIndex = 5;
            this.btnClose.Text = "Close";
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // label2
            // 
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.label2.Location = new System.Drawing.Point(12, 285);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(572, 2);
            this.label2.TabIndex = 2;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(384, 12);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(40, 16);
            this.label4.TabIndex = 11;
            this.label4.Text = "Total:";
            // 
            // labTotal
            // 
            this.labTotal.Location = new System.Drawing.Point(424, 12);
            this.labTotal.Name = "labTotal";
            this.labTotal.Size = new System.Drawing.Size(28, 16);
            this.labTotal.TabIndex = 12;
            this.labTotal.Text = "0";
            this.labTotal.TextAlign = System.Drawing.ContentAlignment.TopRight;
            // 
            // MainForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
            this.ClientSize = new System.Drawing.Size(596, 335);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.labTotal,
                                                                          this.label4,
                                                                          this.label2,
                                                                          this.btnClose,
                                                                          this.btnRefresh,
                                                                          this.btnCommit,
                                                                          this.btnEdit,
                                                                          this.btnDelete,
                                                                          this.btnNew,
                                                                          this.label1,
                                                                          this.viewProducts});
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "MainForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = " ComponentOne DataObjects - Using Objects To Access Data";
            this.Load += new System.EventHandler(this.MainForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.c1DataSet1)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        private void MainForm_Load(object sender, System.EventArgs e)
        {
            RefreshProductList();
        }

        private void btnClose_Click(object sender, System.EventArgs e)
        {
            Close();
        }

        private void MakeItemVisible(ListViewItem lvi)
        {
            viewProducts.SelectedItems.Clear();
            lvi.Focused = true;
            lvi.Selected = true;
            lvi.EnsureVisible();
        }

        private void UpdateTotalLabel()
        {
            labTotal.Text = viewProducts.Items.Count.ToString();
        }

        private void AddProduct()
        {
            C1.Data.C1DataRow rowProduct = null;
            int id = 0;
            ProductForm frm = new ProductForm(" Add Product", c1DataSet1, imageList1);
            rowProduct = c1DataSet1.TableViews["Products"].AddNew();
            frm.SetCurrentRow(rowProduct);
            DialogResult res = frm.ShowDialog();
            if (rowProduct == null)
                rowProduct = c1DataSet1.TableViews["Products"].Rows.Find(id);
            if (res == DialogResult.OK)
            {
                ListViewItem lvi;
                ProductsRow_tableView product = ProductsRow_tableView.Obj(rowProduct);
                if (!product.IsCategoryIDNull() && product.CategoryID > 0 &&
                    product.CategoryID <= imageList1.Images.Count)
                    lvi = new ListViewItem(product.ProductName, product.CategoryID - 1);
                else
                    lvi = new ListViewItem(product.ProductName);
                lvi.Tag = product.ProductID;
                if (!product.IsSupplierIDNull())
                {
                    lvi.SubItems.Add(product.GetSuppliersRow().CompanyName);
                    lvi.SubItems.Add(product.GetSuppliersRow().Country);
                }
                else
                {
                    lvi.SubItems.Add("");
                    lvi.SubItems.Add("");
                }
                viewProducts.Items.Add(lvi);
                MakeItemVisible(lvi);
                UpdateTotalLabel();
            }
            else if (rowProduct != null)
                rowProduct.Delete();
        }

        private void EditProduct()
        {
            ListViewItem lvi = viewProducts.FocusedItem;
            if (lvi != null)
            {
                C1.Data.C1DataRow rowProduct = c1DataSet1.
                    TableViews["Products"].Rows.Find((int)lvi.Tag);
                ProductForm frm = new ProductForm(" Edit Product", c1DataSet1, imageList1);
                frm.SetCurrentRow(rowProduct);
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    ProductsRow_tableView product = ProductsRow_tableView.Obj(rowProduct);
                    lvi.Text = product.ProductName;
                    if (!product.IsCategoryIDNull() && product.CategoryID > 0 &&
                        product.CategoryID <= imageList1.Images.Count)
                        lvi.ImageIndex = product.CategoryID - 1;
                    else
                        lvi.ImageIndex = -1;
                    if (!product.IsSupplierIDNull())
                    {
                        lvi.SubItems[1].Text = product.GetSuppliersRow().CompanyName;
                        lvi.SubItems[2].Text = product.GetSuppliersRow().Country;
                    }
                    else
                    {
                        lvi.SubItems[1].Text = "";
                        lvi.SubItems[2].Text = "";
                    }
                    viewProducts.Sort();
                    MakeItemVisible(lvi);
                }
            }
            else
                MessageBox.Show("There is no selected item.", "UsingObjects",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void DeleteRows()
        {
            if (viewProducts.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("Are you sure you want to delete the item(s)?", "Confirmation",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (ListViewItem lvi in viewProducts.SelectedItems)
                    {
                        c1DataSet1.TableViews["Products"].Rows.Find((int)lvi.Tag).Delete();
                        lvi.Remove();
                    }
                    if (viewProducts.FocusedItem != null)
                        viewProducts.FocusedItem.Selected = true;
                    UpdateTotalLabel();
                }
            }
            else
                MessageBox.Show("There are no items selected.", "UsingObjects",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }

        private void CommitChanges()
        {
            c1DataSet1.Update();
            RefreshProductList();
        }

        private void RefreshProductList()
        {
            c1DataSet1.Fill();
            int focusindex;
            if (viewProducts.FocusedItem != null)
                focusindex = viewProducts.FocusedItem.Index;
            else
                focusindex = -1;
            viewProducts.BeginUpdate();
            viewProducts.Items.Clear();
            C1.Data.C1DataRowCollection rows = c1DataSet1.TableViews["Products"].Rows;
            ListViewItem lvi;
            ProductsRow_tableView product;
            for (int i = 0; i < rows.Count; i++)
            {
                product = ProductsRow_tableView.Obj(rows[i]);
                if (!product.IsCategoryIDNull() && product.CategoryID > 0 &&
                    product.CategoryID <= imageList1.Images.Count)
                    lvi = new ListViewItem(product.ProductName, product.CategoryID - 1);
                else
                    lvi = new ListViewItem(product.ProductName);
                lvi.Tag = product.ProductID;
                if (!product.IsSupplierIDNull())
                {
                    lvi.SubItems.Add(product.GetSuppliersRow().CompanyName);
                    lvi.SubItems.Add(product.GetSuppliersRow().Country);
                }
                else
                {
                    lvi.SubItems.Add("");
                    lvi.SubItems.Add("");
                }
                viewProducts.Items.Add(lvi);
            }
            viewProducts.EndUpdate();
            if (focusindex != -1 && focusindex < viewProducts.Items.Count)
                MakeItemVisible(viewProducts.Items[focusindex]);
            UpdateTotalLabel();
        }

        private void viewProducts_DoubleClick(object sender, System.EventArgs e)
        {
            EditProduct();
        }

        private void viewProducts_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Return:
                    EditProduct();
                    break;
                case Keys.Insert:
                    AddProduct();
                    break;
                case Keys.Delete:
                    DeleteRows();
                    break;
                case Keys.F2:
                    CommitChanges();
                    break;
                case Keys.F3:
                    RefreshProductList();
                    break;
                default:
                    return;
            }
            e.Handled = true;
        }

        private void btnNew_Click(object sender, System.EventArgs e)
        {
            viewProducts.Focus();
            AddProduct();
        }

        private void btnDelete_Click(object sender, System.EventArgs e)
        {
            viewProducts.Focus();
            DeleteRows();
        }

        private void btnEdit_Click(object sender, System.EventArgs e)
        {
            viewProducts.Focus();
            EditProduct();
        }

        private void btnCommit_Click(object sender, System.EventArgs e)
        {
            viewProducts.Focus();
            CommitChanges();
        }

        private void btnRefresh_Click(object sender, System.EventArgs e)
        {
            viewProducts.Focus();
            RefreshProductList();
        }
    }
}
