using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace VisiMath
{
    public class VectorConvertor : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }
        
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(Vector3))
                return true;

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                if (value is Vector3)
                {
                    Vector3 Vector = (Vector3)value;
                    return string.Format("{0} : {1} : {2}",
                            Vector.X.ToString("F"), Vector.Y.ToString("F"), Vector.Z.ToString("F"));
                }
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                string str = value as string;
                
                Vector3 rval = new Vector3();
                int startidx = 0;
                int correctvals = 0;
                for (int i = 0; i < 3; i++)
                {
                    if (startidx >= str.Length)
                        break;
                    int idx = str.IndexOf(':', startidx);
                    float val;
                    if (idx < 0)
                    {
                        if (float.TryParse(str.Substring(startidx), System.Globalization.NumberStyles.Any, culture, out val))
                        {
                            rval[i] = val;
                            correctvals++;
                        }
                        break;
                    }
                    if (float.TryParse(str.Substring(startidx, idx - 1 - startidx), System.Globalization.NumberStyles.Any, culture, out val))
                    {
                        rval[i] = val;
                        correctvals++;
                    }
                    else break;
                    startidx = idx + 1;
                }

                if (correctvals != 3)
                {
                    throw new ArgumentException("String " + str + " doesn't contain valid vector!");
                }
                return rval;
            }
            
            return base.ConvertFrom(context, culture, value);
        }
    }
}
