using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using MSForms = Microsoft.Vbe.Interop.Forms;

// Atrybut integracji z pakietem Office. Identyfikuje klasę początkową dokumentu. Nie wolno modyfikować.
[assembly:System.ComponentModel.DescriptionAttribute("OfficeStartupClass, Version=1.0, Class=CommandBar.OfficeCodeBehind")]

namespace CommandBar
{
	/// <summary>
	/// Zawiera rozszerzenia kodu zarządzanego dla dokumentu.
	/// </summary>
	public class OfficeCodeBehind
	{
		private Office._CommandBarButtonEvents_ClickEventHandler CBarButtonEvent;
		private object oMissing = System.Reflection.Missing.Value;
		private Office.CommandBar CBar;
		private Office.CommandBarComboBox CBarComboBox;
		private Office.CommandBarButton CBarButton;
		/// <summary>
		/// Obiekt aplikacji.
		/// </summary>
		internal Word.Application ThisApplication
		{
			get { return thisApplication;}
		}

		private void CBarButton_Click(Office.CommandBarButton btn, ref bool Cancel)
		{
			// Przygotowanie Worda do odbioru danych
			Word.Selection sln = null;
			sln = ThisApplication.Selection;
			ThisApplication.Options.Overtype = false;

			// Pobranie identyfikatora klienta do oddzielnych pól
			string wrkString = CBarComboBox.Text;
            string[] Customer = wrkString.Split('-');
            
			// Pobranie informacji o kliencie z bazy danych
			SqlConnection conn = new SqlConnection("data source=hp7000\\sql2k;initial catalog=Northwind;integrated security=true");
			SqlCommand cmd = new SqlCommand("select * from customers where customerid = @CustID", conn);
			cmd.Parameters.Add("@CustID", Customer[0]);
			SqlDataReader dr;
			conn.Open();
			dr = cmd.ExecuteReader();

			//Przesłanie danych o adresie klienta do Worda
			while (dr.Read())
			{
				sln.TypeText(dr["CustomerID"].ToString() + "\n");
				sln.TypeText(dr["CompanyName"].ToString() + "\n");
				sln.TypeText(dr["ContactName"].ToString() + "\n");
				sln.TypeText(dr["Address"].ToString() + "\n");
				sln.TypeText(dr["City"].ToString() + ", " + dr["Region"].ToString() + "  ");
				sln.TypeText(dr["PostalCode"].ToString() + "\n");
				sln.TypeText(dr["Country"].ToString());
			}
			dr.Close();
			conn.Close();

		}

		private void WireUpEvents()
		{
			// Konfiguracja zdarzeń Click dla przyciskóew paska poleceń.
			CBarButtonEvent = new Office._CommandBarButtonEvents_ClickEventHandler
				(CBarButton_Click);
			CBarButton.Click += CBarButtonEvent;
		}

		/// <summary>
		/// Obiekt dokumentu.
		/// </summary>
		internal Word.Document ThisDocument
		{
			get { return thisDocument;}
		}
        
		private Word.Application thisApplication = null;
		private Word.Document    thisDocument = null;

		private Word.DocumentEvents2_OpenEventHandler openEvent;
		private Word.DocumentEvents2_CloseEventHandler closeEvent;

		// Określa czy formanty ActiveX zostaną ustawione w trybie Run,
		// nawet jeżeli Word znajduje się w trybie zabezpieczeń wysokiego poziomu.
		// Należy ustawić tę zmnienną na wartość True, jeżeli rozwiązanie
		// wykorzystuje formanty ActiveX.
		private bool toggleActiveXControls = false;
                                          
		#region Generated initialization code

		/// <summary>
		/// Default constructor.
		/// </summary>
		public OfficeCodeBehind()
		{
		}

		private bool designModeClose = false;

		/// <summary>
		/// Required procedure. Do not modify.
		/// </summary>
		/// <param name="application">Application object.</param>
		/// <param name="document">Document object.</param>
		public void _Startup(object application, object document)
		{
			this.thisApplication = application as Word.Application;
			this.thisDocument = document as Word.Document;

			openEvent = new Word.DocumentEvents2_OpenEventHandler (ThisDocument_Open);
			thisDocument.Open += openEvent;

			closeEvent = new Word.DocumentEvents2_CloseEventHandler(ThisDocument_Close);
			((Word.DocumentEvents2_Event)thisDocument).Close += closeEvent;

			// Check if the document is in Design mode.
			if (ThisDocument.FormsDesign == true)
			{
				// Set ActiveX controls to Run mode.
				if (toggleActiveXControls == true)
				{
					ThisDocument.ToggleFormsDesign();
				}

				// Check if the thisDocument is a document and not a template.
				if (thisDocument.Path != "")
				{
					// Set the shutdown procedure to use design mode and then call the Open handler.
					designModeClose = true;
					ThisDocument_Open();

					// Ensure that Open is not called twice.
					thisDocument.Open -= openEvent;
				}
			}
		}

		/// <summary>
		/// Required procedure. Do not modify.
		/// </summary>
		public void _Shutdown()
		{
			// If the document is in design mode, call the Close handler.
			if (designModeClose == true)
				ThisDocument_Close();

			thisApplication = null;
			thisDocument = null;
		}

		/// <summary>
		/// Finds the control with the specified name in ThisDocument.
		/// </summary>
		/// <param name='name'>Name of the control to find.</param>
		/// <returns>
		/// Returns the specified control, or null if it is not found.
		/// </returns>
		object FindControl(string name)
		{
			return FindControl(name, ThisDocument);
		}
 
		/// <summary>
		/// Returns the control with the specified name in the specified document.
		/// </summary>
		/// <param name='name'>Name of the control to find.</param>
		/// <param name='document'>Document object that contains the control.</param>
		/// <returns>Returns the specified control, or null if it is not found.
		/// </returns>
		object FindControl(string name, Word.Document document)
		{
			try
			{
				foreach (Word.InlineShape shape in document.InlineShapes)
				{
					if (shape.Type == Word.WdInlineShapeType.wdInlineShapeOLEControlObject)
					{
						object oleControl = shape.OLEFormat.Object;
						Type oleControlType = oleControl.GetType();
						string oleControlName = (string) oleControlType.InvokeMember("Name", 
							System.Reflection.BindingFlags.GetProperty, null, oleControl, null);
						if (String.Compare(oleControlName, name, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
						{
							return oleControl;
						}
					}
				}

				foreach (Word.Shape shape in document.Shapes)
				{
					if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoOLEControlObject)
					{
						object oleControl = shape.OLEFormat.Object;
						Type oleControlType = oleControl.GetType();
						string oleControlName = (string) oleControlType.InvokeMember("Name", 
							System.Reflection.BindingFlags.GetProperty, null, oleControl, null);
						if (String.Compare(oleControlName, name, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
						{
							return oleControl;
						}
					}
				}
			}
			catch
			{
				// Returns null if the control is not found.
			}
			return null;
		}

		#endregion

		/// <summary>
		/// Metoda wywoływana w momencie otwierania dokumentu.
		/// </summary>
		protected void ThisDocument_Open()
		{
			SetupCommandBar();
			WireUpEvents();
		}

		/// <summary>
		/// Metoda wywoływana w momencie zamykania dokumentu.
		/// </summary>
		protected void ThisDocument_Close()
		{
			// Zapewnienie, aby operacja Close nie została wywołana dwukrotnie.
			designModeClose = false;
		}
		private bool SetupCommandBar()
		{
			try
			{
				// Utworzenie paska poleceń dla bieżącego dokumentu
				ThisApplication.CustomizationContext=ThisDocument;
				CBar = ThisApplication.CommandBars.Add("Customer Form",
					oMissing, oMissing, (object)true);

				// Dodanie listy rozwijanej do paska poleceń
				object objType = Office.MsoControlType.msoControlDropdown;
				CBarComboBox = (Office.CommandBarComboBox)
					((CBar.Controls.Add(objType, oMissing, oMissing,
					oMissing, (object)true)));
				CBarComboBox.Caption = "Wybierz:";
				CBarComboBox.Width = 250;
				CBarComboBox.Style = Office.MsoComboStyle.msoComboLabel;
				CBarComboBox.ListIndex = 0;
				CBarComboBox.BeginGroup=true;

				//Dodanie elementów do listy rozwijanej
				SqlConnection conn = new SqlConnection("data source=hp7000\\sql2k;initial catalog=Northwind;integrated security=true");
				SqlCommand cmd = new SqlCommand("select CustomerID, CompanyName from customers", conn);
				SqlDataReader dr;
				conn.Open();
				dr = cmd.ExecuteReader();
				int i = 0;
				while (dr.Read())
				{
					i += 1;
					CBarComboBox.AddItem(dr["CustomerID"].ToString() + "-" + dr["CompanyName"].ToString(), i);
				}
				dr.Close();
				conn.Close();

				// Dodanie przycisku paska poleceń służącego do wstawiania danych.
				CBarButton = (Office.CommandBarButton)
					(CBar.Controls.Add((object)1, oMissing, oMissing, 
					oMissing, oMissing));
				CBarButton.Style=Office.MsoButtonStyle.msoButtonCaption;
				CBarButton.Caption = "Wstaw";
				
				// Pokazanie nowego paska poleceń.
				CBar.Visible=true;
				return true;
			}
			catch (Exception ex)
			{
				MessageBox.Show("Błąd tworzenia paska poleceń: " + ex.Message, 
					"Customer Form", MessageBoxButtons.OK,
					MessageBoxIcon.Error);
				return false;
			}
		}
	}
}
