﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Globalization;
using SuperMap.Web.Core;

namespace SuperMap.Web.Design
{
    public class ExpandableRectangle2DConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                return this.convertFromString(value as string);
            }
            return base.ConvertFrom(context, culture, value);
        }

        private object convertFromString(string text)
        {
            if (text == null)
            {
                return null;
            }
            string str = text.Trim();
            if (str.Length == 0)
            {
                return null;
            }

            CultureInfo invariantCulture = CultureInfo.InvariantCulture;
            char ch = invariantCulture.TextInfo.ListSeparator[0];
            string[] strArray = str.Split(new char[] { ch });
            double[] numArray = new double[strArray.Length];
            //TODO:
            if (numArray.Length != 4)
            {
                return null;
            }
            for (int i = 0; i < strArray.Length; i++)
            {
                numArray[i] = double.Parse(strArray[i], invariantCulture);
            }

            return new Rectangle2D(numArray[0], numArray[1], numArray[2], numArray[3]);
        }
    }
}
