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

namespace GateBrakeDemo
{
    public class Config
    {
        private static String FILE = "param.xml";
        public static String PATH = System.Windows.Forms.Application.StartupPath + "\\";


        public static String lastip = "";

        /// <summary>
        /// 读取XML配置文件节点内容
        /// </summary>
        /// <param name="node"></param>
        /// <param name="name"></param>
        /// <returns>value</returns>
        private static String ReadXmlNode(XmlElement node, String name)
        {
            return node.GetElementsByTagName(name)[0].InnerText;
        }

        private static XmlNodeList ReadNodeFromNode(XmlElement node, String name)
        {
            return node.GetElementsByTagName(name);
        }

        /// <summary>
        /// 向XML配置文件里添加新的节点，并指定内容
        /// </summary>
        /// <param name="XMLDom"></param>
        /// <param name="node"></param>
        /// <param name="name"></param>
        /// <param name="text"></param>
        private static void AddTextNode(XmlDocument XMLDom, XmlElement node, String name, String text)
        {
            XmlElement e = XMLDom.CreateElement(name);
            e.InnerText = text;
            node.AppendChild(e);
        }
        /// <summary>
        /// 向XML配置文件里添加新的节点
        /// </summary>
        /// <param name="XMLDom"></param>
        /// <param name="node"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        private static XmlElement AddNode(XmlDocument XMLDom, XmlElement node, String name)
        {
            XmlElement e = XMLDom.CreateElement(name);
            node.AppendChild(e);
            return e;
        }


        public static void LoadParam()
        {
            Config cfg = new Config();
            try
            {
                XmlDocument XMLDom = new XmlDocument();
                XMLDom.Load(PATH + FILE);
                XmlElement root = XMLDom.DocumentElement;
                lastip = ReadXmlNode(root, "lastip");
            }
            catch (Exception ex)
            {
                lastip = "127.0.0.1";
                SaveToFile();
            }
        }

        public static void SaveToFile()
        {
            XmlDocument XMLDom = new XmlDocument();
            XMLDom.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><set></set>");
            XmlElement root = XMLDom.DocumentElement;

            AddTextNode(XMLDom, root, "lastip", "" + lastip);
            try
            {

                XMLDom.Save(PATH + FILE);
            }
            catch (Exception e)
            {

            }
        }
    
    }
}
