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

namespace PushPlatform.Common.Util
{
    public class ConfigUtil
    {
        private string path;

        public ConfigUtil(string confPath)
        {
            path = confPath;
        }

        /// <summary>
        /// 设置xml配置
        /// </summary>
        /// <param name="configName">节点名称</param>
        /// <param name="value">值</param>
        public void Set(string configName, string value)
        {
            if (!FileUtil.Exists(path))
                Create();

            XDocument xml = XDocument.Load(path);
            var obj = xml.Root.Elements().FirstOrDefault(p => p.Name == configName);

            if (obj != null)
                obj.Value = value;
            else
                xml.Root.Add(new XElement(configName, value));

            xml.Save(path);
        }

        /// <summary>
        /// 读取xml配置
        /// </summary>
        /// <param name="configName"></param>
        /// <returns>如果没有该配置则返回空字符串</returns>
        public string Read(string configName)
        {
            if (FileUtil.Exists(path))
            {
                XDocument xml = XDocument.Load(path);

                var obj = xml.Root.Elements().FirstOrDefault(p => p.Name == configName && !string.IsNullOrEmpty(p.Value));

                return obj != null ? obj.Value : string.Empty;
            }
            else
            {
                Create();
                return string.Empty;
            }
        }

        private void Create()
        {
            System.IO.FileInfo info = new System.IO.FileInfo(path);
            FileUtil.ExistsPath(info.DirectoryName, true);//创建目录

            //创建Xdocument对象
            XDocument xDoc = new XDocument();

            //创建一个根节点，config
            XElement xEle = new XElement("config");

            //加载到XML文档
            xDoc.Add(xEle);

            //保存文档
            xDoc.Save(path);
        }

        public void SetHos(string configName, string value)
        {
            if (!FileUtil.Exists(path))
                Create();

            XDocument xml = XDocument.Load(path);
            var obj = xml.Root.Elements().FirstOrDefault(p => p.Name == configName);

            if (obj != null)
                obj.Value = value;
            else
                xml.Root.Add(new XElement(configName, value));

            xml.Save(path);
        }
    }
}
