using System;
using System.ComponentModel;
using System.Xml;

namespace Quadarax.Foundation.Common.Xml.Extensions
{
    public static class XmlNodeExt
    {
        public static T GetAttribute<T>(this XmlNode node, string sAttributeName, bool bMandatory, T oDefaultValue)
        {
            if (string.IsNullOrEmpty(node.GetAttribute(sAttributeName)))
            {
                if (bMandatory)
                    throw new Exception(
                        $"Missing mandatory attribute '{sAttributeName}' in element '{node.Name}'");
                return oDefaultValue;
            }
            return (T) TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(node.GetAttribute(sAttributeName));
        }

        public static string GetAttribute(this XmlNode node, string attributeName)
        {
            if (node?.Attributes == null)
                return string.Empty;

            foreach (XmlAttribute attr in node.Attributes)
            {
                if (attr.Name == attributeName)
                    return attr.Value;
            }

            return string.Empty;
        }
    }
}
