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

namespace CssSpriteGenerator
{
    /// <summary>
    /// Used to store a collection of image attributes, such as src and style.
    /// The key is the name of the attribute. *** That name must be all lowercase. ***
    /// The value is the value of the attribute.
    /// </summary>
    public class ImageAttributeDictionary : Dictionary<string, string>
    {
        /// <summary>
        /// Returns a string with attribute-value pairs, such that the string can be dropped in an html tag.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return ToString(null, null);
        }

        /// <summary>
        /// Version of ToString
        /// </summary>
        /// <param name="excludes">
        /// If this is null, no filtering. If not null, an attribute will not be added to output if it is excludes.
        /// </param>
        /// <param name="copiedImgAttributesRegex">
        /// If this is null, no filtering. If not null, only attributes that match this regular expression make it to the output.
        /// </param>
        /// <returns></returns>
        public string ToString(List<string> excludes, Regex copiedImgAttributesRegex)
        {
            StringBuilder resultSb = new StringBuilder();

            foreach (KeyValuePair<String, String> imageAttribute in this)
            {
                string attributeName = imageAttribute.Key.ToLower();
                string attributeValue = imageAttribute.Value;

                if ((copiedImgAttributesRegex == null) ||
                    (copiedImgAttributesRegex.IsMatch(attributeName)))
                {
                    if ((excludes == null) || (!excludes.Contains(attributeName)))
                    {
                        resultSb.AppendFormat(@" {0}=""{1}""", attributeName, attributeValue);
                    }
                }
            }

            return resultSb.ToString();
        }

        /// <summary>
        /// Returns the value of the given attribute.
        /// If the attribute doesn't exist, returns empty string.
        /// </summary>
        /// <param name="attributeName">
        /// Make sure this is all lowercase!
        /// </param>
        /// <returns></returns>
        public string AttributeValue(string attributeName)
        {
            string attributeValue;
            if (TryGetValue(attributeName, out attributeValue))
            {
                return attributeValue;
            }

            return "";
        }
    }
}
