//
// MySqlFactory.cs
//
// Author:
//       Carsten Sonne Larsen <cs@innolan.dk>
//
// Copyright (c) 2016 Carsten Sonne Larsen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#if MYSQL
using System;
using System.Data.Common;
using System.Text;
using MySql.Data.MySqlClient;

namespace Ntp.Data.Provider
{
    public sealed class MySqlFactory : SqlDatabaseFactory
    {
        internal MySqlFactory()
        {
        }

        private const string CreateDatabaseSql =
            "CREATE DATABASE IF NOT EXISTS {0};";

        private const string CheckTableSql =
            "SELECT table_name " +
            "FROM information_schema.tables " +
            "WHERE table_schema = '{0}' " +
            "AND table_name = '{1}';";

        public override void CreateDatabase()
        {
            DbConnection connection = CreateGenericConnection();
            connection.Open();
            DbCommand command = Instance.CreateCommand();
            command.Connection = connection;
            command.CommandText = String.Format(CreateDatabaseSql, Config.Name);
            command.Prepare();
            connection.Close();
        }

        public override string PrepareSql(string sql)
        {
            return sql.Replace("[", String.Empty).Replace("]", String.Empty);
        }

        public override string PrepareCheckTableSql(string table)
        {
            return PrepareSql(String.Format(CheckTableSql, Config.Name, table));
        }

        public override string PrepareCreateTableSql(string sql)
        {
            return PrepareSql(String.Format(sql, "INT NOT NULL AUTO_INCREMENT", " ENGINE=INNODB"));
        }

        public override string PrepareInsertSql(string sql)
        {
            return PrepareSql(String.Format(sql, "SELECT LAST_INSERT_ID()"));
        }

        public override DbConnection CreateGenericConnection()
        {
            return new MySqlConnection(BuildConnectionString(false));
        }

        public override DbConnection CreateConnection()
        {
            return new MySqlConnection(BuildConnectionString());
        }

        private string BuildConnectionString(bool includeName = true)
        {
            var b = new StringBuilder();
            b.AppendFormat("Server={0};", Config.Host);

            if (Config.Port != null)
                b.AppendFormat("Port={0};", Config.Port);

            if (includeName)
                b.AppendFormat("Database={0};", Config.Name);

            b.AppendFormat("Uid={0};", Config.User);
            b.AppendFormat("Pwd={0};", Config.Pass);

            // TODO: Inlcude SSL options
            //SSL Mode=Required;CertificateFile=C:\folder\client.pfx;CertificatePassword=pass;

            return b.ToString();
        }

        public override DbCommand CreateCommand()
        {
            return new MySqlCommand();
        }

        public override DbParameter CreateParameter()
        {
            return new MySqlParameter();
        }

        public override DbParameter CreateParameter(string name, object value)
        {
            return new MySqlParameter(name, value);
        }
    }
}
#endif