using System;
using System.IO;
using System.Xml.Serialization;

namespace ProjectManagementSystem.Config
{
    public class CConfiManager
    {
        public static CustomConfig customConfig = new CustomConfig();

        private static string m_strPath = "";
        private static string _GlobalDataFilePath = "";

        public static void Init()
        {
            InitConfigPath();
            InitGlobalData();
        }

        private static void InitConfigPath()
        {
            //获取到文件完整路径
            string s = System.Reflection.Assembly.GetExecutingAssembly().Location;
            //获取到文件所在目录
            FileInfo finfo = new FileInfo(s);
            string BaseDirectory = finfo.DirectoryName;

            m_strPath = Path.Combine(BaseDirectory, "PMS", "Config");

            _GlobalDataFilePath = Path.Combine(m_strPath, "CConfigSetting.xml");
        }

        private static void ExsitConfigPath()
        {
            DirectoryInfo dir = new DirectoryInfo(m_strPath);
            if (!dir.Exists)
            {
                dir.Create();
            }
        }

        public static void InitGlobalData()
        {
            //反序列化
            try
            {
                ExsitConfigPath();
                XmlSerializer serializer = new XmlSerializer(customConfig.GetType());
                if (!File.Exists(_GlobalDataFilePath))
                {
                    SaveGlobalData();
                }
                else
                {
                    using (TextReader tr = new StreamReader(_GlobalDataFilePath))
                    {
                        customConfig = (CustomConfig)serializer.Deserialize(tr);
                    }
                }

            }
            catch (Exception e)
            {
                string strlog = e.Message;
            }
        }

        public static void SaveGlobalData()
        {
            try
            {
                ExsitConfigPath();
                XmlSerializer serializer = new XmlSerializer(customConfig.GetType());
                using (TextWriter tw = new StreamWriter(_GlobalDataFilePath))
                {
                    serializer.Serialize(tw, customConfig);
                }
            }
            catch
            { }
        }
    }
}
