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

namespace CommonUI.Tool
{
  public class XMLTool
  {
      private static XMLTool mInstance = null;
      protected Hashtable mDocs = new Hashtable();

      public XMLTool()
      {
          mInstance = this;
      }

      public static XMLTool Instance
      {
          get 
          {
              if (mInstance == null) { new XMLTool(); }
              return mInstance; 
          }
      }

      public virtual XmlDocument LoadXML(string fileName)
      {
          if (mDocs.ContainsKey(fileName)) { return (XmlDocument)(mDocs[fileName]);}
             


          return null;
      }

      public virtual XmlDocument LoadLocalXML(string fileName)
      {
          return null;
      }

      public virtual XmlNode GetXmlNode(string fileName, string nodeName)
      {
          XmlDocument doc = LoadXML(fileName);
          XmlNode xml = doc.FirstChild;
          if (xml != null)
          {
              XmlNode data = xml.NextSibling;
              return GetXmlNode(nodeName, data);
          }
          else
          {
              return null;
          }
      }

      private XmlNode GetXmlNode(string nodeName, XmlNode root)
      {
          XmlNode result = null;

          if (root.Attributes["name"] != null && nodeName.Equals(root.Attributes["name"].Value))
          {
              result = root;
              return result;
          }

          XmlNode subNode = root.FirstChild;

          while (subNode != null && result == null)
          {
              result = GetXmlNode(nodeName, subNode);
              subNode = subNode.NextSibling;
          }

          return result;
      }

      public XmlNode FindChild(XmlNode e, string childName)
      {
          foreach (XmlNode cc in e.ChildNodes)
          {
              if (cc.Name == childName)
              {
                  return cc;
              }
          }
          return null;
      }

      public XmlDocument GetXml(byte[] data_)
      {

          if (data_ != null)
          {
              XmlDocument xmlDoc = new XmlDocument();
              int l = System.Text.Encoding.UTF8.GetString(data_).Length;

              byte[] data = new byte[l];
              if (data_[0] != 60)
                  Array.Copy(data_, 3, data, 0, l - 3);
              else
                  data = data_;

              if (data != null)
              {
                  string _data = System.Text.Encoding.UTF8.GetString(data);

                  if (_data != null)
                      xmlDoc.LoadXml(_data);

                  data_ = null;
                  data = null;

                  //mDocs.Add(mFileName, xmlDoc);
                  return xmlDoc;
              }
          }
          return null;
      }
  }
}