//
// PostgreSqlFactory.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 PGSQL
using System;
using System.Data.Common;
using System.Text;
using Npgsql;

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

        private const string CreateDatabaseSql1 =
            "SELECT COUNT(*) FROM pg_database WHERE datname = lower('{0}');";

        private const string CreateDatabaseSql2 =
            "CREATE DATABASE {0};";

        private const string CheckTableSql =
            "SELECT * " +
            "FROM information_schema.tables " +
            "WHERE table_catalog = lower('{0}') " +
            "AND table_name = lower('{1}');";

        public override void CreateDatabase()
        {
            DbConnection connection = CreateGenericConnection();
            connection.Open();

            DbCommand command = Instance.CreateCommand();
            command.Connection = connection;
            command.CommandText = String.Format(CreateDatabaseSql1, Config.Name);
            command.Prepare();
            int count = Convert.ToInt32(command.ExecuteScalar());

            if (count == 0)
            {
                command.CommandText = String.Format(CreateDatabaseSql2, Config.Name);
                command.Prepare();
                command.ExecuteNonQuery();
            }

            connection.Close();
        }

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

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

        public override string PrepareCreateTableSql(string sql)
        {
            string sql2 =
                sql.
                    Replace("UNIQUE KEY", "UNIQUE").
                    Replace("BIT(1)", "BOOL");

            return PrepareSql(String.Format(sql2, "SERIAL", String.Empty));
        }

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

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

        public override DbConnection CreateConnection()
        {
            return new NpgsqlConnection(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);
            else
                b.Append("Database=postgres;");

            b.AppendFormat("User Id={0};", Config.User);
            b.AppendFormat("Password={0};", Config.Pass);

            return b.ToString();
        }

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

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

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