// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// 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.

using System;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using Ntp.Common.Log;
using Ntp.Data.Log;

namespace Ntp.Data.Schema
{
    public sealed class VersionController
    {
        public VersionController(ISqlFactory factory, LogBase log)
        {
            this.factory = factory;
            this.log = log;
        }

        private const string CreateSql = "CREATE TABLE version (number INT NOT NULL PRIMARY KEY);";
        private const string SelectSql = "SELECT number FROM version;";
        private const string UpdateSql = "UPDATE version SET number=@number;";
        private const string InsertSql = "INSERT INTO version (number) VALUES (0);";
        private readonly ISqlFactory factory;
        private readonly LogBase log;

        public int FindCurrentVersion()
        {
            if (CheckTable())
                return SelectVersion();

            CreateTable();
            InsertTable();
            return -1;
        }

        public void SetCurrentVersion(IVersionChanges version)
        {
            if (version == null)
            {
                log.VersionTableParamError();
                return;
            }

            IDbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                var command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = UpdateSql;
                command.Parameters.Add(factory.CreateParameter("@number", version.VersionNumber));
                command.Prepare();
                log.SqlExecute(command.CommandText, command.Parameters);
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.VersionTableUpdateError(e);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }

            log.SchemaUpdated(version.VersionText);
        }

        [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities")]
        private bool CheckTable()
        {
            IDbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                var command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = factory.PrepareCheckTableSql("version");
                command.Prepare();
                log.SqlExecute(command.CommandText);
                var reader = command.ExecuteReader();
                return reader.Read();
            }
            catch (Exception e)
            {
                log.VersionTableCreateError(e);
                return false;
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        private void CreateTable()
        {
            IDbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                var command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = CreateSql;
                command.Prepare();
                log.SqlExecute(command.CommandText);
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.VersionTableCreateError(e);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }

            log.VersionTableCreated();
        }

        private void InsertTable()
        {
            IDbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                var command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = InsertSql;
                command.Prepare();
                log.SqlExecute(command.CommandText);
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.VersionTableInsertError(e);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        private int SelectVersion()
        {
            IDbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                var command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = SelectSql;
                command.Prepare();
                log.SqlExecute(command.CommandText);
                var result = command.ExecuteScalar();
                return Convert.ToInt32(result);
            }
            catch (Exception e)
            {
                log.VersionTableFetchError(e);
                return -1;
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }
    }
}