//==============================================================
//  版权所有：深圳杰文科技
//  文件名：DataSourceSetting.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.IO;

namespace Infrastructure.Utilities
{
	[Serializable]
	public class DataSourceSetting
	{
		public enum DbTypes
		{
			None = 0,
			SqlServer = 1,
			Oracle = 2,
			Oracle_tns = 3,
			MySql = 4,
			SqlLite = 5
		}

		public Guid Id
		{
			get;
			set;
		}

		public string Token
		{
			get;
			set;
		}

		public DbTypes DbType
		{
			get
			{
				return (DbTypes)this.DbTypeId;
			}
			set
			{
				this.DbTypeId = (int)value;
			}
		}

		public int DbTypeId
		{
			get;
			set;
		}

		public string Server
		{
			get;
			set;
		}
		public int Port
		{
			get;
			set;
		}
		public string DbName
		{
			get;
			set;
		}
		public string User
		{
			get;
			set;
		}
		public string Password
		{
			get;
			set;
		}

		public string ConnectionString
		{
			get
			{
				return GenerateConnectionString();
			}
		}

		private string GenerateConnectionString()
		{
			if (this.Server.IsNullOrEmpty() || this.User.IsNullOrEmpty())
			{
				return "";
			}

			if (this.DbType == DbTypes.SqlServer)
			{
				return "Data Source={0}; Initial Catalog={1}; User Id={2}; Password={3};".Fmt(Server, DbName, User, Password);
			}
			else if (this.DbType == DbTypes.Oracle)
			{
				return "Data Source={0}:{1}/{2};User Id={3};Password={4};".Fmt(Server, Port, DbName, User, Password);
			}
			else if (this.DbType == DbTypes.Oracle_tns)
			{
				return "Data Source={0};User Id={1};Password={2};".Fmt(DbName, User, Password);
			}
			else if (this.DbType == DbTypes.SqlLite)
			{
				return "Data Source={0};Version=3;".Fmt(DbName);
			}
			else
			{
				throw new NotImplementedException();
			}
		}

		public const string KEY = "JewenKey";
		public const string IV = "Jewen_IV";

		public void Save(string fileName)
		{
			string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + ".config");
			ObjectSerializer.Serialize(this, path, KEY, IV);
		}

		public static DataSourceSetting Load(string fileName)
		{
			string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName + ".config");
			if (!File.Exists(path))
			{
				return null;
			}

			object obj = ObjectSerializer.Deserialize(path, KEY, IV);
			DataSourceSetting setting = obj as DataSourceSetting;
			if (setting == null)
			{
				setting = new DataSourceSetting();
				setting.Id = Guid.NewGuid();
				setting.DbType = DataSourceSetting.DbTypes.None;
			}
			return setting;
		}

	}
}
