#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.Windows.Forms;
using dataMagus.Common;
using dataMagus.Common.PlugIn.Generator;
using dataMagus.Common.Physical;
using dataMagus.Common.Physical.Objectoriented;
#endregion

namespace dataMagus.Forms.Elements
{
	/// <summary>
	/// Extended data form for managing physical objectoriented properties.
	/// </summary>
	public partial class PhysicalObjectorientedPropertyForm : Form
	{
		#region Members
		/// <summary>
		/// Physical objectoriented property data the form is based on.
		/// </summary>
		private PhysicalObjectorientedProperty _property = null;
		#endregion
		
		#region Constructors / Destructors
		/// <summary>
        /// Default constructor.
        /// </summary>
		public PhysicalObjectorientedPropertyForm()
		{
			InitializeComponent();
		}
		#endregion
		
		#region Properties
		/// <summary>
		/// Physical objectoriented property data the form is based on.
		/// </summary>
		public PhysicalObjectorientedProperty Property 
		{
			get { return this._property; }
			set { this._property = 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._property.Name = this.nameTextBox.Text.Trim();
	            DataType selectedDataType = (DataType)this.datatypeCombo.SelectedItem;
	            this._property.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.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);
            }
            //TODO: Sort Liste
            this.datatypeCombo.DataSource = new BindingSource(datatypeList, null);
            this.datatypeCombo.DataSource = datatypeList;

			// fill generators
			List<IGenerator> generators = GeneratorManager.Instance.FindInterfaceType(typeof(IObjectorientedGenerator));
            //TODO: Sort liste
			this.generatorCombo.DisplayMember = "Name";
			this.generatorCombo.DataSource = generators;
		}
		
		/// <summary>
		/// Load the data into the form.
		/// </summary>
		private void LoadData()
		{
			if (null != this._property)
			{
				this.nameTextBox.Text = this._property.Name;
                this.datatypeCombo.SelectedItem = this._property.DataType;
            }
		}
		
		/// <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)
			{
				this.errorProvider.SetError(this.nameTextBox, "Please fill in the name.");
				isValid = false;
			}
			
			if (-1 == this.datatypeCombo.SelectedIndex)
			{
				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 PhysicalObjectorientedPropertyFormLoad(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)
	            {
	                IObjectorientedGenerator generator = (IObjectorientedGenerator)this.generatorCombo.SelectedItem;
	
	                PhysicalObjectorientedProperty cloned = (PhysicalObjectorientedProperty)this._property.Clone();
	                // update clone with actual data from the form
	                cloned.DataType = (DataType)this.datatypeCombo.SelectedItem;
	                cloned.Name = this.nameTextBox.Text;
	
	                GeneratorControl ctrl = generator.GetExtendedPropertyDataControl(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 PhysicalObjectorientedPropertyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
        	try
			{
	            List<IPhysicalSchema> currentSchemas = PhysicalSchemaManager.Instance.FindType(typeof(PhysicalObjectorientedSchema));
	            IPhysicalSchema clonedSchema = (IPhysicalSchema)currentSchemas[0].Clone();
	
	            List<IGenerator> generators = GeneratorManager.Instance.FindInterfaceType(typeof(IObjectorientedGenerator));
	            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 tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
        	try
			{
	            if (this.tabControl1.SelectedTab == this.targetTab)
	            {
	                this.GeneratorComboSelectedIndexChanged(sender, e);
	            }
			}
			catch (Exception ex)
			{
				MessageForm.ShowDialog(ex);
			}
        }
		#endregion
	}
}
