using System;
using System.Xml;

namespace Creditcall.ChipDna.Client
{
    public abstract class BaseConfigParser
    {
        private const string NOT_LOADED_MESSAGE = "XML Document has not been loaded...";

        public XmlDocument XmlDocument;
        protected XmlElement RootNode { get { return XmlDocument.DocumentElement; } }

       
        protected string GetElementByProperties(XmlElement rootnode, string propertyName)
        {
            try
            {
                var attributeNode = rootnode.GetAttributeNode(propertyName);
                if (attributeNode != null) return attributeNode.Value;
                return rootnode.GetElementsByTagName(propertyName).Count > 0 ? rootnode.GetElementsByTagName(propertyName)[0].InnerText : null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        protected void LoadXmlFile(string configFileName)
        {
            XmlDocument = new XmlDocument();
            XmlDocument.Load(configFileName);
        }

        protected XmlNodeList GetNodesByTagName(string tagName)
        {
            return GetNodesByTagName(XmlDocument.DocumentElement, tagName);
        }


        protected XmlNodeList GetNodesByTagName(XmlElement rootnode, string tagName)
        {
            if (XmlDocument != null)
            {
                return rootnode.GetElementsByTagName(tagName);
            }
            throw new InvalidOperationException(NOT_LOADED_MESSAGE);
        }

        public string GetElementByName(XmlElement rootnode, string nodeName)
        {
            try
            {
                return rootnode.GetElementsByTagName(nodeName).Count != 0 ? rootnode.GetElementsByTagName(nodeName)[0].InnerText : null;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
