using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.WizardFramework;
using System.Configuration;
using System.Collections;
using System.ComponentModel.Design;
using Howest.Guidance.DataAccess.CodeGeneration.ObjectModel.Mappings.Helpers;
using Howest.Guidance.DataAccess.CodeGeneration.ObjectModel;
using Howest.Guidance.DataAccess.CustomWizardPages.Helpers;
using System.Windows.Forms.Design;
using Howest.Guidance.DataAccess.CodeGeneration.ObjectModel.Mappings;
using Howest.Guidance.DataAccess.CodeGeneration.ObjectModel.Mappings.Enums;

namespace Howest.Guidance.DataAccess.CustomWizardPages
{
	public partial class EntityCommandMapperCP : CustomWizardPage
	{
		#region Fields

		private ArrayList _entitiesSqlStatementMappings;
		ConnectionStringSettings connectionSettings;
		string cnstring;

		#endregion

		#region Arguments

		/// <summary>
		/// Gets or sets the entities stored procedure mappings.
		/// </summary>
		/// <value>The entities stored procedure mappings.</value>
		[RecipeArgument]
		public ArrayList EntitiesSqlStatementMappings
		{
			get
			{
				return _entitiesSqlStatementMappings;
			}
			set
			{
				_entitiesSqlStatementMappings = value;
			}
		}

		#endregion
		public EntityCommandMapperCP(WizardForm parent)
			: base(parent)
		{
			InitializeComponent();
		}

		/// <summary>
		/// Called when [activated].
		/// </summary>
		public override void OnActivated()
		{
			IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
			connectionSettings = (ConnectionStringSettings)dictservice.GetValue("ConnectionSettings");

			if (dictservice.GetValue("EntitiesSqlStatementMappings") == null)
			{
				//First Time
				SetControlProperties(false);
				cnstring = connectionSettings.ConnectionString;
			}
			else
			{
				if (cnstring != connectionSettings.ConnectionString)
				{
					SetControlProperties(false);
					cnstring = connectionSettings.ConnectionString;
				}
				else
				{
					SetControlProperties(true);
				}

				dictservice.SetValue("EntitiesSqlStatementMappings", null);
			}

			SaveArgument();
			base.OnActivated();
		}

		private void lstEntities_SelectedIndexChanged(object sender, EventArgs e)
		{
			Entity entity = (Entity)lstEntities.SelectedItem;
			RefreshMappings(entity);
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			cmnuAdd.Show(btnAdd, new Point(0, btnAdd.Height));
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities) ||
			   !UIGuard.IsListBoxSelected(lstMappings))
			{
				return;
			}

			IUIService uiService = (IUIService)GetService(typeof(IUIService));
			if (uiService.ShowMessage("Do you want to delete the mapping?", null, MessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				Entity entity = (Entity)lstEntities.SelectedItem;

				//UIHelper.Finder = lstMappings.SelectedItem.ToString();
				EntitySqlStatementMapping mapping = entity.SqlStatementMappings.Find(delegate(EntitySqlStatementMapping mapList)
				{
					return mapList.MappingName == lstMappings.SelectedItem.ToString();
				});

				entity.SqlStatementMappings.Remove(mapping);

				lstMappings.Items.Remove(lstMappings.SelectedItem);

				if (lstMappings.Items.Count > 0)
				{
					lstMappings.SelectedIndex = 0;
					btnDelete.Enabled = true;
					btnEdit.Enabled = true;
				}
				else
				{
					btnDelete.Enabled = false;
					btnEdit.Enabled = false;
				}

				RefreshMappings(entity);
			}
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities) ||
			   !UIGuard.IsListBoxSelected(lstMappings))
			{
				return;
			}

			Entity entity = (Entity)lstEntities.SelectedItem;
			//UIHelper.Finder = lstOperations.SelectedItem.ToString();
			EntitySqlStatementMapping mapping = entity.SqlStatementMappings.Find(delegate(EntitySqlStatementMapping mapList) {
				return mapList.MappingName == lstMappings.SelectedItem.ToString();
			});

			if (mapping != null)
			{
				Form form;

				if (mapping.MappingType == SqlStatementMappingType.Output)
				{
					form = new SqlOutputMappingForm(
						connectionSettings,
						entity,
						//mapping.OperationType,
						Operation.Edit,
						mapping.MappingName);
				}
				else
				{
					form = new SqlInputMappingForm(connectionSettings, entity, Operation.Edit, mapping.Statements[0].OperationType, mapping.MappingName
						/*connectionSettings,
						entity,
						mapping.OperationType,
						Operation.Edit,
						mapping.OperationName*/);
				}

				if (form.ShowDialog(this) == DialogResult.OK)
				{
					RefreshMappings(entity);
				}
			}
		}

		private void SetControlProperties(bool syncEntities)
		{
			IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
			ArrayList entities = (ArrayList)dictservice.GetValue("Entities");
			List<Entity> clonedEntities = new List<Entity>();
			foreach (Entity ent in entities)
			{
				clonedEntities.Add(ent);
			}
			clonedEntities = clonedEntities = ClonerHelper.CloneEntities(clonedEntities);

			if (syncEntities)
			{
				ArrayList currentEntities = (ArrayList)dictservice.GetValue("EntitiesSqlStatementMappings");

				foreach (Entity currentEntity in currentEntities)
				{
					Entity entity = clonedEntities.Find(delegate(Entity entList) {
						return entList.Name == currentEntity.Name;
					});// UIHelper.FindEntity(clonedEntities, currentEntity.Name);

					if (entity != null)
					{
						clonedEntities.Remove(entity);
						clonedEntities.Add(currentEntity);
					}
				}
			}

			Cursor.Current = Cursors.WaitCursor;

			//try
			//{
			//    ProvideDefaultMappings(clonedEntities, UIHelper.GetStoredProcedures(connectionSettings));
			//}
			//catch
			//{
			//    IUIService uiService = (IUIService)GetService(typeof(IUIService));
			//    uiService.ShowMessage("There was an error trying to obtain the list of stored procedures.");
			//}

			Cursor.Current = Cursors.Default;
			UIHelper.FillEntitiesListBox(lstEntities, clonedEntities);
			SetControls();
			EnableControls(lstEntities.Items.Count > 0);

			if (lstEntities.Items.Count > 0)
			{
				lstEntities.SelectedIndex = 0;
				RefreshMappings((Entity)lstEntities.SelectedItem);
			}
		}

		private void RefreshMappings(Entity entity)
		{
			lstMappings.Items.Clear();

			foreach (EntitySqlStatementMapping mapping in entity.SqlStatementMappings)
			{
				lstMappings.Items.Add(mapping.MappingName);
			}

			if (lstMappings.Items.Count > 0)
			{
				lstMappings.SelectedIndex = 0;
				btnDelete.Enabled = true;
				btnEdit.Enabled = true;
			}
			else
			{
				btnDelete.Enabled = false;
				btnEdit.Enabled = false;
			}

			SaveArgument();
		}

		private void SetControls()
		{
			lstEntities.DisplayMember = "Entity.Name";
		}

		private void EnableControls(bool enable)
		{
			btnAdd.Enabled = enable;
			btnDelete.Enabled = enable;
			btnEdit.Enabled = enable;
		}

		private void SaveArgument()
		{
			ArrayList mapping = GetEntitySqlStatementMappings();
			IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
			dictservice.SetValue("EntitiesSqlStatementMappings", mapping);
		}

		private ArrayList GetEntitySqlStatementMappings()
		{
			ArrayList mappings = new ArrayList();

			foreach (Entity item in lstEntities.Items)
			{
				mappings.Add(item);
			}

			return mappings;
		}

		private void cmnuItemSQLGet_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities))
			{
				return;
			}

			Entity entity = (Entity)lstEntities.SelectedItem;

			SqlOutputMappingForm form = new SqlOutputMappingForm(
				connectionSettings,
				entity);

			if (form.ShowDialog(this) == DialogResult.OK)
			{
				RefreshMappings(entity);
			}
		}

		private void cmnuItemSQLInsert_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities))
			{
				return;
			}

			Entity entity = (Entity)lstEntities.SelectedItem;

			SqlInputMappingForm form = new SqlInputMappingForm(
				connectionSettings,
				entity, OperationType.InsertOne);

			if (form.ShowDialog(this) == DialogResult.OK)
			{
				RefreshMappings(entity);
			}
		}

		private void cmnuItemSQLUpdate_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities))
			{
				return;
			}

			Entity entity = (Entity)lstEntities.SelectedItem;

			SqlInputMappingForm form = new SqlInputMappingForm(
				connectionSettings,
				entity, OperationType.UpdateOne);

			if (form.ShowDialog(this) == DialogResult.OK)
			{
				RefreshMappings(entity);
			}
		}

		private void cmnuItemSQLDelete_Click(object sender, EventArgs e)
		{
			if (!UIGuard.IsListBoxSelected(lstEntities))
			{
				return;
			}

			Entity entity = (Entity)lstEntities.SelectedItem;

			SqlInputMappingForm form = new SqlInputMappingForm(
				connectionSettings,
				entity, OperationType.DeleteOne);

			if (form.ShowDialog(this) == DialogResult.OK)
			{
				RefreshMappings(entity);
			}
		}

	}
}
