using Dapper;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Linq;
using EVCB_OCPP.WEBAPI.Helpers;
using EVCB_OCPP.Domain;
using System.Threading.Tasks;

namespace EVCB_OCPP.WEBAPI.Services
{
    public interface ICustomerService
    {
        string GetAPIKey(Guid partnerId);

        Task<string> GetAPIKeyAsync(Guid partnerId);
    }

    public class CustomerService : ICustomerService
    {
        private readonly SqlConnectionFactory<MainDBContext> mainDbConnectionFactory;

        //readonly string mainConnectionString;
        public CustomerService(SqlConnectionFactory<MainDBContext> mainDbConnectionFactory)
        {
            //mainConnectionString = configuration.GetConnectionString("MainDBContext");
            this.mainDbConnectionFactory = mainDbConnectionFactory;
        }

        public string GetAPIKey(Guid partnerId)
        {
            return GetAPIKeyAsync(partnerId).Result;
        }

        public async Task<string> GetAPIKeyAsync(Guid partnerId)
        {
            string key = string.Empty;
            var parameters = new DynamicParameters();
            parameters.Add("@Id", partnerId, DbType.Guid, ParameterDirection.Input);
            using (SqlConnection conn = await mainDbConnectionFactory.CreateAsync())
            {
                string strSql = "Select ApiKey from [dbo].[Customer] where Id=@Id; ";
                key = await conn.ExecuteScalarAsync<string>(strSql, parameters, null, EVCBConfiguration.DB_DefaultConnectionTimeout);
            }
            return key;

        }
    }
}