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

namespace ImageTemplateNet
{
    /// <summary>
    /// This class is used to load the configuration of ImageTemplate.NET from web.config.
    /// </summary>
    public class ImageGenerationConfigurationSectionHandler: IConfigurationSectionHandler
    {
        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            ImageTemplateConfiguration config = new ImageTemplateConfiguration(
                getConfigAttribute(section, "config", true),
                getConfigAttribute(section, "imageCacheDir", true),
                getConfigAttribute(section, "defaultCacheTimeSeconds", true)
                );
            return config;
        }

        #endregion

        /// <summary>
        /// Gets the setting with the given name
        /// </summary>
        /// <param name="section">The XML node which the setting is an attribute of</param>
        /// <param name="attributeName">The name of the attribute</param>
        /// <param name="required">true if an exception should be thrown if the attribute is missing</param>
        /// <returns>The value of the attribute</returns>
        private string getConfigAttribute(System.Xml.XmlNode section, String attributeName, bool required)
        {
            XmlAttribute attrib = section.Attributes[attributeName];
            if (attrib == null)
            {
                if (required)
                {
                    throw new ConfigurationException("The required attribute '" + attributeName + "' is missing");
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return attrib.Value;
            }
        }

    }
}
