//
// VersionController.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.

using System;
using System.Data;
using System.Data.Common;
using Ntp.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())
            {
                CreateTable();
                InsertTable();
                return -1;
            }

            return SelectVersion();
        }

        private bool CheckTable()
        {
            DbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                DbCommand command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = factory.PrepareCheckTableSql("version");
                command.Prepare();
                DbDataReader reader = command.ExecuteReader();
                return (reader.Read());
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to create version table.", Severity.Error);
                log.WriteLine(e, Severity.Trace);
                return false;
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        private void CreateTable()
        {
            DbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                DbCommand command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = CreateSql;
                command.Prepare();
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to create version table.", Severity.Error);
                log.WriteLine(e, Severity.Trace);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }

            log.WriteLine("Created new version table.", Severity.Notice);
        }

        private int SelectVersion()
        {
            DbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                DbCommand command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = SelectSql;
                command.Prepare();
                object result = command.ExecuteScalar();
                return Convert.ToInt32(result);
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to fetch version number from database.", Severity.Error);
                log.WriteLine(e, Severity.Trace);
                return -1;
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        private void InsertTable()
        {
            DbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                DbCommand command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = InsertSql;
                command.Prepare();
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to insert into version table.", Severity.Error);
                log.WriteLine(e, Severity.Trace);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }
        }

        public void SetCurrentVersion(IVersionChanges version)
        {
            if (version == null)
            {
                log.WriteLine("Internal error: Version cannot be null.", Severity.Error);
                return;
            }

            DbConnection connection = null;

            try
            {
                connection = factory.CreateConnection();
                connection.Open();
                DbCommand command = factory.CreateCommand();
                command.Connection = connection;
                command.CommandText = UpdateSql;
                command.Parameters.Add(factory.CreateParameter("@number", version.VersionNumber));
                command.Prepare();
                command.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                log.WriteLine("Failed to update version table.", Severity.Error);
                log.WriteLine(e, Severity.Trace);
            }
            finally
            {
                if (connection != null && connection.State == ConnectionState.Open)
                    connection.Close();
            }

            log.WriteLine(String.Format(
                "Database schema updated to version {0}.", version.VersionText),
                Severity.Notice
                );
        }
    }
}