using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Reflection;
using System.Xml;

namespace Northwind
{
	/// <summary>
	/// Summary description for ProjectInstaller.
	/// </summary>
	[RunInstaller(true)]
	public class ProjectInstaller : System.Configuration.Install.Installer
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public ProjectInstaller()
		{
			// This call is required by the Designer.
			InitializeComponent();

			// TODO: Add any initialization after the 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 Component 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()
		{
			components = new System.ComponentModel.Container();
		}
		#endregion

		private void UpdateConfigFile(string ServerName)
		{

			if(string.Empty==ServerName)
				throw new InstallException("ServerName not specified");
	        
			// Use reflection to find the location of the config file.
			System.Reflection.Assembly Asm = 
				System.Reflection.Assembly.GetExecutingAssembly();
			System.IO.FileInfo FileInfo = new 
				System.IO.FileInfo(Asm.Location + ".config");
			if(!FileInfo.Exists)
				throw new InstallException("Missing config file");

			//Load the config file into the XML DOM.
			System.Xml.XmlDocument XmlDocument = new System.Xml.XmlDocument();
			XmlDocument.Load(FileInfo.FullName);

			//Find the right node and change it to the new value.
			Boolean FoundIt = false;
			foreach(XmlNode Node in XmlDocument["configuration"]["appSettings"])
			{
				if("add"==Node.Name)
				{// skip any comments
					if("ConnectionString"==Node.Attributes.GetNamedItem("key").Value)
					{
						Node.Attributes.GetNamedItem("value").Value = 
							String.Format("Server={0};Database=NorthWind;Integrated Security=True" 
							, ServerName);
						FoundIt = true;
					}
				}
			}

			if(!FoundIt)
				throw new InstallException( 
					"Config file did not contain a ConnectionString setting");

			//Write out the new config file.
			XmlDocument.Save(FileInfo.FullName);

		}

		public override void Install(IDictionary stateSaver) 
		{
			base.Install (stateSaver);
			UpdateConfigFile(this.Context.Parameters[
				"ServerName"]);
			MainClass.WriteInstalledVersion();
		}
	}
}
