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

namespace SMAT_CE
{
    public class XMLWorker
    {
        // 用该XmlWriter向xml文件写入内容
        XmlTextWriter _writer = null;

        /// <summary>
        /// 创建XmlWriter
        /// </summary>
        /// <param name="strFilePath">要生成的XML数据文件全路径</param>
        /// <returns>true表示成功;false表示失败</returns>
        public bool CreateDataFile(string strFilePath)
        {
            try
            {
                _writer = new XmlTextWriter(strFilePath, null);
                _writer.Formatting = Formatting.Indented;
                _writer.WriteStartDocument();

                return true;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return false;
            }
        }

        /// <summary>
        /// 写入到xml文件
        /// </summary>
        public void Save()
        {
            try
            {
                _writer.WriteEndDocument();
                _writer.Flush();
                _writer.Close();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 编写节点开始标记
        /// </summary>
        /// <param name="NodeName">节点名称</param>
        public void WriteStartElement(string nodeName)
        {
            try
            {
                _writer.WriteStartElement(nodeName);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 编写节点结束标记
        /// </summary>
        public void WriteEndElement()
        {
            try
            {
                _writer.WriteEndElement();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 编写节点属性,如写入<table dest="CORP_Info">中的dest="CORP_Info"
        /// </summary>
        /// <param name="name">属性名称</param>
        /// <param name="value">属性值</param>
        public void WriteAttributeString(string name, string value)
        {
            try
            {
                _writer.WriteAttributeString(name, value);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 编写节点内容值,如写入<field>num</field>
        /// </summary>
        /// <param name="field">Element名称</param>
        /// <param name="value">Element值</param>
        public void WriteElementString(string field, string value)
        {
            try
            {
                _writer.WriteElementString(field, value);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
        /// <summary>
        /// create a xml file
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <param name="startNode"></param>
        public void CreateNode(string xmlPath, string nodeName)
        {
            XMLWorker worker = new XMLWorker();
            try
            {
                bool ok = worker.CreateDataFile(xmlPath);
                //if (!ok)
                //{
                //    msg = "Error encountered while creating script file (*.xml)!"; ;                  
                //    return false;
                //}
                worker.WriteStartElement(nodeName);
                //worker.WriteStartElement("RSM");
                worker.WriteEndElement();
                worker.Save();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                if (worker != null)
                {
                    worker = null;
                }
                //if (msg != "")
                //{
                //    //MessageBox.Show(msg, Language.Localization.MessageTitle, MessageBoxButtons.OK, icon);
                //}
            }
        }

        /// <summary>
        /// 往现有xml文件追加节点片段
        /// </summary>
        /// <param name="xmlPath">要追加文件的路径</param>
        /// <param name="startNode">在指定的节点追加节点片段</param>
        /// <param name="sectionNode">节点片段信息</param>
        public void AppendNode(string xmlPath, string startNode, SectionNode sectionNode)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlPath);
                XmlNode root = xmlDoc.SelectSingleNode(startNode); //xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
                //创建一个父节点    
                XmlElement parentNode = xmlDoc.CreateElement(sectionNode.ParentNode.NodeName);
                //XmlElement xe1 = xmlDoc.CreateElement("book");//创建一个<book>节点
                //给这个父节点设置属性
                foreach (var item in sectionNode.ParentNode.NodeAttributes)
                {
                    //xe1.SetAttribute("genre", "李赞红");//设置该节点genre属性
                    //xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点ISBN属性
                    parentNode.SetAttribute(item.Key, item.Value);
                }
                foreach (var item in sectionNode.ChildNodes)
                {
                    XmlElement childNode = xmlDoc.CreateElement(item.NodeName);
                    childNode.InnerText = item.NodeText;//设置文本节点
                    foreach (var childAttribute in item.NodeAttributes)
                    {
                        parentNode.SetAttribute(childAttribute.Key, childAttribute.Value);
                    }
                    parentNode.AppendChild(childNode);//添加到<book>节点中
                }
                root.AppendChild(parentNode);//添加到<bookstore>节点中
                xmlDoc.Save(xmlPath);

            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 修改指定节点的值和属性
        /// </summary>
        /// <param name="xmlPath">待修改文件</param>
        /// <param name="updatedParentNodeName">待修改节点所在的父节点名称</param>
        /// <param name="updatedChildNode">待修改的节点</param>
        public void UpdateNode(string xmlPath, string updatedParentNodeName, List<Node> lstNode)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                XmlNodeList nodeList = xmlDoc.SelectSingleNode(updatedParentNodeName).ChildNodes;//获取bookstore节点的所有子节点
                foreach (Node node in lstNode)
                {
                    foreach (XmlNode xn in nodeList)//遍历所有子节点
                    {
                        XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
                        if (xe.Name == node.NodeName)
                        {
                            xe.InnerText = node.NodeText;
                            foreach (var item in node.NodeAttributes)
                            {
                                xe.SetAttribute(item.Key, item.Value);
                            }
                            break;
                        }
                    }
                }
                xmlDoc.Save(xmlPath);//保存。
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }


        public void DeleteNode(string xmlPath, string deletedParentNodeName, Node deletedChildNode)
        {

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlPath);
            XmlNode xn = xmlDoc.SelectSingleNode("bookstore");
            XmlNodeList xnl = xn.ChildNodes;
            foreach (XmlNode xnf in xnl)
            {
                XmlElement xe = (XmlElement)xnf;
                Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
                Console.WriteLine(xe.GetAttribute("ISBN"));


                XmlNodeList xnf1 = xe.ChildNodes;
                foreach (XmlNode xn2 in xnf1)
                {
                    Console.WriteLine(xn2.InnerText);//显示子节点点文本
                }
            }
        }

        public bool SearchNode(string xmlPath, string NodeName)
        {

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);
                XmlElement root = xmlDoc.DocumentElement;
                XmlNode node = root.SelectSingleNode(string.Format("//Settings//{0}", NodeName));//查找指定节点
                if (node == null)
                {
                    return false;
                }
                return true;
                //获取根节点的所有子节点  
                //XmlNodeList childNodes = xmlDoc.SelectSingleNode("Settings").ChildNodes;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return false;               
            }
        }

    }// XMLWorker
}
