using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
using System.Collections.Generic;
using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using System.Xml.Serialization;

namespace DbCommon.Function
{
    public class Config
    {
        private static Config m_instance;
        private static readonly object m_locker = new object();
        public static Config Instance
        {
            get
            {
                if (m_instance == null)
                {
                    lock (m_locker)
                    {
                        if (m_instance == null)
                        {
                            m_instance = new Config();
                        }
                    }
                }
                return m_instance;
            }
        }

        public static DbCommonConfig DbConfig = new DbCommonConfig();

        public string WmsConnString
        {
            get
            {
                return $"Data Source=\"{DbConfig.DataSource}\";Initial Catalog=\"{DbConfig.InitialCatalog}\";uid={DbConfig.uid};pwd={DbConfig.pwd}";
            }
        }

        public string HostString
        {
            get { return DbConfig.DataSource; }
        }

        private Config()
        {
            try
            {
                string s = System.Reflection.Assembly.GetExecutingAssembly().Location;
                FileInfo finfo = new FileInfo(s);

                string currPath = finfo.DirectoryName;
                string configDir = Path.Combine(currPath, "PMS", "Config");
                string configFile = Path.Combine(configDir, "DbCommonConfig.xml");

                DirectoryInfo dir = new DirectoryInfo(configDir);
                if (!dir.Exists)
                {
                    dir.Create();
                }

                XmlSerializer serializer = new XmlSerializer(DbConfig.GetType());
                if (!File.Exists(configFile))
                {
                    using (TextWriter tw = new StreamWriter(configFile))
                    {
                        serializer.Serialize(tw, DbConfig);
                    }
                }
                else
                {
                    using (TextReader tr = new StreamReader(configFile))
                    {
                        DbConfig = (DbCommonConfig)serializer.Deserialize(tr);
                    }
                }
            }
            catch (Exception)
            {
            }
        }
    }

    public class DbCommonConfig
    {
        public string DataSource { get; set; } = ".";
        public string InitialCatalog { get; set; } = "WMS";
        public string uid { get; set; } = "sa";
        public string pwd { get; set; } = "123";
    }
}
