using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;

using BS.Shared;
using BS.Shared.Extensions;

namespace BeWo.Converter
{
    public class UserRightTypeArrayConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(UserRightType[]))
            {
                return true;
            }
            else if (sourceType == typeof(String))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string text = value as String;
            if (text != null)
            {
                List<UserRightType> rightTypes = new List<UserRightType>();

                List<string> vals = text.Split(",");

                foreach (var item in vals)
                {
                    object urt = Enum.Parse(typeof(UserRightType), item.Trim());
                    if (urt != null)
                    {
                        rightTypes.Add((UserRightType)urt);
                    }
                }

                return rightTypes.ToArray();
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            return base.ConvertTo(context, culture, value, destinationType);
        }

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return base.GetStandardValues(context);
        }
    }
}