using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace CssSpriteGenerator
{
    [ConfigurationCollection(typeof(GroupConfigurationElement), CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
    public class GroupConfigurationElementCollection : ConfigurationElementCollection
    {
        private static ConfigurationPropertyCollection _properties;
        protected override ConfigurationPropertyCollection Properties
        {
            get { return _properties; }
        }

        static GroupConfigurationElementCollection()
        {
            _properties = new ConfigurationPropertyCollection();
        }

        public GroupConfigurationElementCollection()
        {
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }

        public GroupConfigurationElement this[int index]
        {
            get { return (GroupConfigurationElement)base.BaseGet(index); }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new GroupConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            // Create a readable element key, because if there is a duplicate, that key
            // will be shown in an exception.

            // Allow multiple groups with an empty group name.
            string groupName = (element as GroupConfigurationElement).GroupName;
            if (string.IsNullOrEmpty(groupName))
            {
                groupName = Guid.NewGuid().ToString();
            }

            return "groupName=" + groupName;
        }
    }
}
