using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace Performance.Repository
{
    /// <summary>
    /// 创建连接
    /// </summary>
    public class ConnectionBuilder
    {
        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="type"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static IDbConnection Create(DatabaseType type, string connectionString)
        {
            switch (type)
            {
                case DatabaseType.MySql:
                    return new MySqlConnection(connectionString);
                case DatabaseType.SqlServer:
                    return new SqlConnection(connectionString);
                default:
                    throw new Exception($"nonsupport {DatabaseType.MySql}");
            }
        }

        /// <summary>
        /// 创建连接字符串
        /// </summary>
        /// <param name="type"></param>
        /// <param name="ip"></param>
        /// <param name="database"></param>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string GetConnectionString(DatabaseType type, string ip, string database, string uid, string pwd)
        {
            string connectionString = "";
            switch (type)
            {
                case DatabaseType.MySql:
                    connectionString = $"Server={ip};Database={database};Uid={uid};Pwd={pwd};connection timeout=12000;pooling=true;charset=utf8;Convert Zero Datetime=True;port=3306;Allow User Variables=True;;";
                    break;
                case DatabaseType.SqlServer:
                    connectionString = $"data source={ip};initial catalog={database};user id={uid};password={pwd};connection timeout=12000;";
                    break;
                default:
                    throw new Exception($"nonsupport {DatabaseType.MySql}");
            }
            return connectionString;
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <param name="type"></param>
        /// <param name="ip"></param>
        /// <param name="database"></param>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static IDbConnection Create(DatabaseType type, string ip, string database, string uid, string pwd)
        {
            string connectionString = GetConnectionString(type, ip, database, uid, pwd);
            return Create(type, connectionString);
        }

    }

}
