using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.RecipeFramework.Extensions.Converters;
using System.ComponentModel;

namespace Howest.Guidance.DataAccess.Converters
{
	public class ValueTypeFromStringConverter : StringConverter
	{
		Type[] valueTypes = new Type[] { 
			typeof(int),
			typeof(string),
			typeof(byte),
			typeof(float),
			typeof(double),
			typeof(short),
			typeof(DateTime),
			typeof(long),
			typeof(uint),
			typeof(ushort),
			typeof(char),
			typeof(bool),
			typeof(ulong),
			typeof(byte[]),
			typeof(object)
		};

		public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
		{
			if (value is string)
			{
				Type type = Type.GetType((string)value);
				if (type == null)
				{
					throw new ArgumentException("Type not found.", "value");
				}
				return type;
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType != typeof(string))
			{
				return base.ConvertTo(context, culture, value, destinationType);
			}
			return ((Type)value).ToString();

		}

		public override StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
		{
			//return base.GetStandardValues(context);
			StandardValuesCollection col = new StandardValuesCollection(valueTypes);
			return col;
		}

		public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context)
		{
			return true;
		}

		public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
		{
			return true;
		}
	}
}
