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

namespace TFSWrappers
{
    internal static class Functions
    {
        internal static void SetXmlNodeInnerText(XmlDocument xmlDocument, string XPath, XmlNamespaceManager xmlNamespaceManager, string innerText,
            string fileName)
        {
            XmlNode xmlNode = xmlDocument.SelectSingleNode(XPath, xmlNamespaceManager);
            if (xmlNode != null)
            {
                xmlNode.InnerText = innerText;
            }
            else
            {
                if ((innerText != null) && (innerText != String.Empty))
                {
                    string parentNodeXPath = XPath.Substring(0, XPath.LastIndexOf('/'));
                    string nodeName = XPath.Substring(XPath.LastIndexOf('/') + 4);
                    XmlNode parentXmlNode = xmlDocument.SelectSingleNode(parentNodeXPath, xmlNamespaceManager);
                    XmlNode newXmlNode = xmlDocument.CreateNode(XmlNodeType.Element, nodeName, Constants.NamespaceUri);
                    newXmlNode.InnerText = innerText;
                    parentXmlNode.AppendChild(newXmlNode);
                }
            }
        }

        internal static string GetXmlNodeInnerText(XmlDocument xmlDocument, string XPath, XmlNamespaceManager xmlNamespaceManager)
        {
            XmlNode xmlNode = xmlDocument.SelectSingleNode(XPath, xmlNamespaceManager);
            if (xmlNode != null)
            {
                return xmlNode.InnerText;
            }
            return String.Empty;
        }

        internal static void RemoveXmlNode(XmlDocument xmlDocument, string XPath, XmlNamespaceManager xmlNamespaceManager,
            string fileName)
        {
            XmlNode xmlNode = xmlDocument.SelectSingleNode(XPath, xmlNamespaceManager);
            if (xmlNode != null)
            {
                xmlNode.ParentNode.RemoveChild(xmlNode);
            }
            else
            {
                throw new ApplicationException(String.Format("Error removing xml node. Node {0} does not exist.", XPath));
            }
        }
    }
}
