﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace MIS.Data
{

    using Dapper;

    public class DbContextBase
    {
        protected IEnumerable<T> QuerySql<T>(IDbConnection connection, string action, string sql, object parameters = null)
        {
            return connection.Query<T>(sql, parameters);
        }

        protected IEnumerable<T> TimedQuerySql<T>(IDbConnection connection, string action, string sql, object parameters = null)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            var result = connection.Query<T>(sql, parameters);

            stopwatch.Stop();
            LogTimeTaken(action, stopwatch);

            return result;
        }

        protected void ExecuteSql(IDbConnection connection, string action, string sql, object parameters = null)
        {
            connection.Execute(sql, parameters);
        }

        protected void TimedExecuteSql(IDbConnection connection, string action, string sql, object parameters = null)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            connection.Execute(sql, parameters);

            stopwatch.Stop();
            LogTimeTaken(action, stopwatch);
        }

        protected IEnumerable<T> QueryStoredProcedure<T>(IDbConnection connection, string storedProcedure, object parameters = null)
        {
            return connection.Query<T>(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
        }
        
        protected IEnumerable<T> TimedQueryStoredProcedure<T>(IDbConnection connection, string storedProcedure, object parameters = null)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            var result = connection.Query<T>(storedProcedure, parameters, commandType: CommandType.StoredProcedure);

            stopwatch.Stop();
            LogTimeTaken(storedProcedure, stopwatch);

            return result;
        }

        protected void ExecuteStoredProcedure(IDbConnection connection, string storedProcedure, object parameters = null)
        {
            connection.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
        }

        protected void TimedExecuteStoredProcedure(IDbConnection connection, string storedProcedure, object parameters = null)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            connection.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure);

            stopwatch.Stop();
            LogTimeTaken(storedProcedure, stopwatch);
        }

        protected void LogTimeTaken(string storedProcedure, Stopwatch stopwatch)
        {
            Console.WriteLine(">    Called: {0} | Time elapsed: {1}", storedProcedure, stopwatch.Elapsed);
        }
    }
}
