using AzonEntityLibrary;
using System;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;

namespace ProductDocument
{
    public partial class ThisDocument
    {
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            this.Application.DocumentBeforeSave += Application_DocumentBeforeSave;
        }

        private void ThisDocument_Shutdown(object sender, System.EventArgs e)
        {

        }

        void Application_DocumentBeforeSave(Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)
        {
            SaveToDatabase();
        }

        private bool SaveToDatabase()
        {
            bool result = false;
            try
            {
                using (DepomuzEntities context = new DepomuzEntities())
                {
                    Product newProduct = new Product
                    {
                        Name = TextBoxName.Text,
                        Description = TextBoxDescription.Text,
                        InsertDate = DateTimePickerEnterDate.Value,
                        ListPrice = System.Convert.ToDecimal(TextBoxListPrice.Text),
                        RealPrice = System.Convert.ToDecimal(TextBoxRealPrice.Text),
                        Quantity = System.Convert.ToInt32(NumericUpDownQuantity.Value),
                        Notes = TextBoxNotes.Text
                    };
                    context.Products.Add(newProduct);
                    context.SaveChanges();

                    result = true;

                    MessageBox.Show(
                        string.Format("Selim Ustam ürün {0} numarası ile dosyalandı"
                        ,newProduct.ProductId.ToString()));
                } 
            }
            catch(Exception excp)
            {
                MessageBox.Show("Selim Ustam beni arar mısın? Sanırım işlemin sırasında bir hata oluştu");
                //TODO@Rukiye burada oluşan istisnaları kendime mail atayım ve hatta log dosyasına yazdırayım
            }

            return result;
        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            SaveToDatabase();
        }

        #region VSTO Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.ButtonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
            this.Startup += new System.EventHandler(this.ThisDocument_Startup);
            this.Shutdown += new System.EventHandler(this.ThisDocument_Shutdown);
        }

        #endregion
    }
}
