#region Copyright and GPL
/*************************************************************************
 * dataMagus - The open source database learning software
 * Copyright (C) 2007 by all authors
 * Authors: Monika Schwitter (monsy@gmx.ch)
 *          Jürg Zgraggen (j.zgraggen@ejaz.net)
 *          HSLU (Hochschule Luzern - Technik+Architektur)
 * 
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *************************************************************************/
#endregion
#region Using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.Serialization;
using System.Windows.Forms;
using dataMagus.Common;
using dataMagus.Common.Physical;
using dataMagus.Common.Physical.Relational;
using dataMagus.Common.PlugIn.Generator;
#endregion

namespace dataMagus.Forms.Elements
{
	/// <summary>
	/// Extended data form for managing physical relational columns.
	/// </summary>
	public partial class PhysicalRelationalColumnForm : Form
	{
		#region Members
		/// <summary>
		/// Physical relational column data the form is based on.
		/// </summary>
		private PhysicalRelationalColumn _column = null;
		#endregion
		
		#region Constructors / Destructors
		/// <summary>
        /// Default constructor.
        /// </summary>
		public PhysicalRelationalColumnForm()
		{
			InitializeComponent();
		}
		#endregion
		
		#region Properties
		/// <summary>
		/// Physical relational column data the form is based on.
		/// </summary>
		public PhysicalRelationalColumn Column 
		{
			get { return this._column; }
			set { this._column = value; }
		}
		#endregion
		
		#region Methodes
        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
		private void OkButtonClick(object sender, EventArgs e)
		{
			try
			{
				if (!this.FormIsValidate())
				{
					return;
				}
	
				this._column.Name = this.nameTextBox.Text.Trim();
				this._column.AllowNulls = this.allowsNullCheck.Checked;
				DataType selectedDataType = (DataType)this.datatypeCombo.SelectedItem;
				this._column.DataType = selectedDataType;
				
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
		}
		
        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
		private void CancelButtonClick(object sender, EventArgs e)
		{
			try
			{
				this.DialogResult = DialogResult.Cancel;
				this.Close();
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
		}
		
		/// <summary>
		/// Clean the data on the form for primitive state.
		/// </summary>
		private void CleanData()
		{
			// clean
			this.datatypeCombo.DataSource = null;
			this.allowsNullCheck.Checked = false;
			this.nameTextBox.Clear();

			// fill datatypes
            List<DataType> datatypeList = new List<DataType>();
            IEnumerator dataTypesEnumerator = DataContainer.Instance.PhysicalData.GetDataTypes();
            while (dataTypesEnumerator.MoveNext())
            {
                DataType datatype = (DataType)dataTypesEnumerator.Current;
                datatypeList.Add(datatype);
            }
            this.datatypeCombo.DataSource = new BindingSource(datatypeList, null);
            this.datatypeCombo.DataSource = datatypeList;

			// fill generators
			List<IGenerator> generators = GeneratorManager.Instance.FindInterfaceType(typeof(IRelationalGenerator));
			this.generatorCombo.DisplayMember = "Name";
			this.generatorCombo.DataSource = generators;
		}
		
		/// <summary>
		/// Load the data into the form.
		/// </summary>
		private void LoadData()
		{
			if (null != this._column)
			{
				this.nameTextBox.Text = this._column.Name;
				this.datatypeCombo.SelectedItem = this._column.DataType;
				this.allowsNullCheck.Checked = this._column.AllowNulls;

                this.datatypeCombo.Enabled = !this._column.IsPartOfForeignKey;
                this.allowsNullCheck.Enabled = !this._column.IsPartOfPrimaryKey;
			}
		}
		
		/// <summary>
		/// Validate the data on the form and set the specified error provider for the
		/// invalide control.
		/// </summary>
		/// <returns>
		/// true indicates that the form is valid, false indicates that the form
		/// contains invalid data which sould not be used until corrected.
		/// </returns>
		private bool FormIsValidate()
		{
			bool isValid = true;
			this.errorProvider.Clear();
			
			if (0 == this.nameTextBox.Text.Trim().Length)
			{   //TODO: ins Resource-File
				this.errorProvider.SetError(this.nameTextBox, "Please fill in the name.");
				isValid = false;
			}
			
			if (-1 == this.datatypeCombo.SelectedIndex)
            {//TODO: ins Resource-File
				this.errorProvider.SetError(this.datatypeCombo, "Please choose the datatype.");
				isValid = false;
			}

			return isValid;
		}
		
        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
		private void PhysicalRelationalColumnFromLoad(object sender, EventArgs e)
		{
			try
			{
				this.CleanData();
				this.LoadData();
				this.nameTextBox.Focus();
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
		}
		
        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
		private void GeneratorComboSelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				this.generatorPanel.Controls.Clear();
				if (-1 != this.generatorCombo.SelectedIndex)
				{
					IRelationalGenerator generator = (IRelationalGenerator)this.generatorCombo.SelectedItem;
					
	                PhysicalRelationalColumn cloned = (PhysicalRelationalColumn)this._column.Clone();
	                // update clone with actual data from the form
	                cloned.DataType = (DataType)this.datatypeCombo.SelectedItem;
	                cloned.Name = this.nameTextBox.Text;
	                cloned.AllowNulls = this.allowsNullCheck.Checked;
	
					GeneratorControl ctrl = generator.GetExtendedColumnDataControl(cloned);
					if (null != ctrl)
					{
						ctrl.Dock = DockStyle.Fill;
						this.generatorPanel.Controls.Add(ctrl);
					}
				}
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
        }

        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
        private void PhysicalRelationalColumnForm_FormClosing(object sender, FormClosingEventArgs e)
        {
        	try
			{
	            List<IPhysicalSchema> currentSchemas = PhysicalSchemaManager.Instance.FindType(typeof(PhysicalRelationalSchema));
	            IPhysicalSchema clonedSchema = (IPhysicalSchema)currentSchemas[0].Clone();
	                
	            List<IGenerator> generators = GeneratorManager.Instance.FindInterfaceType(typeof(IRelationalGenerator));
	            foreach (IGenerator generator in generators)
	            {
	                generator.CleanExtendedData(clonedSchema);
	            }
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
        }

        /// <summary>
        /// Event handler.
        /// </summary>
        /// <param name="sender">Sender object.</param>
        /// <param name="e">EventArgs</param>
        private void tabControl_TabIndexChanged(object sender, EventArgs e)
        {
        	try
			{
	            if (this.tabControl.SelectedTab == this.targetTab)
	            {
	                this.GeneratorComboSelectedIndexChanged(sender, e);
	            }
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
        }
        #endregion
    }
}
