using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Dapper;

namespace Valg.EVA.Skanning.Entity.SqlConnection
{
    public static class AsyncDataAccessExtensions
    {
        public static async Task ExecuteAsync(this ISqlConnectionFactory factory, string query, object parameters = null, int? timeOut = DataAccessExtensions.defaultCommandTimeOut)
        {
            var asyncExecute = Task.Run(async () =>
            {
                using (var connection = factory.CreateSqlConnection())
                {
                    var commandTimeOut = factory.GetCommandTimeOut(timeOut);

                    await connection.OpenAsync().ConfigureAwait(false);
                    await connection.ExecuteAsync(query, parameters, commandTimeout: commandTimeOut).ConfigureAwait(false);
                }
            });

            await ExecuteAndCheckForConcurrencyExceptionsAsync(asyncExecute);
        }

        public static async Task SP_ExecuteAsync(this ISqlConnectionFactory factory, string spName, object parameters = null, int? timeOut = DataAccessExtensions.defaultCommandTimeOut)
        {
            var asyncExecute = Task.Run(async () =>
            {
                using (var connection = factory.CreateSqlConnection())
                {
                    var commandTimeOut = factory.GetCommandTimeOut(timeOut);

                    await connection.OpenAsync().ConfigureAwait(false);
                    await connection.ExecuteAsync(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: commandTimeOut).ConfigureAwait(false);
                }
            });

            await ExecuteAndCheckForConcurrencyExceptionsAsync(asyncExecute);
        }

        public static async Task<T> SP_ExecuteAsync<T>(this ISqlConnectionFactory factory, string spName, object parameters = null, int? timeOut = DataAccessExtensions.defaultCommandTimeOut)
        {
            var asyncExecute = Task.Run(async () =>
            {
                using (var connection = factory.CreateSqlConnection())
                {
                    var commandTimeOut = factory.GetCommandTimeOut(timeOut);

                    await connection.OpenAsync().ConfigureAwait(false);
                    return await connection.QueryAsync<T>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: commandTimeOut).ConfigureAwait(false);
                }
            });

            var result = await ExecuteAndCheckForConcurrencyExceptionsAsync(asyncExecute).ConfigureAwait(false);
            return result.SingleOrDefault();
        }

        private static async Task<T> ExecuteAndCheckForConcurrencyExceptionsAsync<T>(Task<T> task)
        {
            try
            {
                return await task.ConfigureAwait(false);
            }
            catch (SqlException ex)
            {
                if (ex.Class == 16 && ex.Number == 50000 && ex.Message == "ConcurrencyError")
                {
                    throw new DBConcurrencyException($"Concurrency error in procedure {ex.Procedure}", ex);
                }
                else
                {
                    throw;
                }
            }
        }

        private static async Task ExecuteAndCheckForConcurrencyExceptionsAsync(Task task)
        {
            try
            {
                await task.ConfigureAwait(false);
            }
            catch (SqlException ex)
            {
                if (ex.Class == 16 && ex.Number == 50000 && ex.Message == "ConcurrencyError")
                {
                    throw new DBConcurrencyException($"Concurrency error in procedure {ex.Procedure}", ex);
                }
                else
                {
                    throw;
                }
            }
        }

        public static async Task<T> SP_GetAsync<T>(this ISqlConnectionFactory factory, string spName, object parameters = null, int? timeOut = DataAccessExtensions.defaultCommandTimeOut)
        {
            using (var connection = factory.CreateSqlConnection())
            {
                var commandTimeOut = factory.GetCommandTimeOut(timeOut);

                await connection.OpenAsync().ConfigureAwait(false);

                var resultCollection = await connection.QueryAsync<T>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: commandTimeOut).ConfigureAwait(false);
                return resultCollection.SingleOrDefault();
            }
        }

        public static async Task<IEnumerable<T>> SP_GetListAsync<T>(this ISqlConnectionFactory factory, string spName, object parameters = null, int? timeOut = DataAccessExtensions.defaultCommandTimeOut)
        {
            using (var connection = factory.CreateSqlConnection())
            {
                var commandTimeOut = factory.GetCommandTimeOut(timeOut);
                await connection.OpenAsync().ConfigureAwait(false);

                var resultCollection = await connection.QueryAsync<T>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: commandTimeOut).ConfigureAwait(false);
                return resultCollection;
            }
        }
    }
}
