using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using Config = System.Configuration.Configuration;
using System.Data.Common;
using System.Configuration;
using System.Windows.Forms.Design;

namespace Howest.Guidance.Extensions.Actions.Configuration
{
	public class SetConnectionStringEntryAction : ConfigurableAction
	{
		#region Input

		private Config _configuration;

		[Input(Required=true)]
		public Config Configuration
		{
			get { return _configuration; }
			set { _configuration = value; }
		}

		private string _connectionStringEntryName;

		[Input(Required=true)]
		public string ConnectionStringEntryName
		{
			get { return _connectionStringEntryName; }
			set { _connectionStringEntryName = value; }
		}

		private string _connectionStringEntryValue;

		[Input(Required=true)]
		public string ConnectionStringEntryValue
		{
			get { return _connectionStringEntryValue; }
			set { _connectionStringEntryValue = value; }
		}

		private string _providerName;

		[Input(Required=true)]
		public string ProviderName
		{
			get { return _providerName; }
			set { _providerName = value; }
		}

		#endregion

		public override void Execute()
		{
			ConnectionStringsSection connectionStringsSection = (ConnectionStringsSection)_configuration.GetSection("connectionStrings");

			if (connectionStringsSection.ConnectionStrings[_connectionStringEntryName] == null)
			{
				try
				{
					DbProviderFactory factory = DbProviderFactories.GetFactory(_providerName);
					throw new ArgumentException();
				}
				catch (ArgumentException)
				{
					//TODO: Send warning to user that provider is not configured in machine.config
				}
				//Add Entry
				connectionStringsSection.ConnectionStrings.Add(
					new ConnectionStringSettings(
						_connectionStringEntryName,
						_connectionStringEntryValue,
						_providerName));
			}
			else
			{
				//Update Entry
				connectionStringsSection.ConnectionStrings[_connectionStringEntryName].ConnectionString =
					ConnectionStringEntryValue;
			}
		}

		public override void Undo()
		{
			
		}
	}
}
