using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EVCB_OCPP.WSServer.Helper
{
    public static class DbExtention
    {
        public static async Task<(bool, int)> SaveChangesUntilSuccessAsync(this DbContext context)
        {
            bool result = false;
            int rows = 0;
            do
            {
                (result, rows) = await context.TrySaveChangesAsync();
            }
            while (!result);
            return (result, rows);
        }

        public static async Task<(bool, int)> TrySaveChangesAsync(this DbContext context)
        {
            int affectedRows = 0;
            try
            {
                affectedRows = await context.SaveChangesAsync();
                return (true, affectedRows);
            }
            catch (Exception e)
            {
                return (false, affectedRows);
            }
        }

        public static void AddInsertMeterValueRecordSqlParameters(this List<SqlParameter> sqlParameters,
            string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
            ,int contextId, int formatId, int measurandId, int phaseId
            ,int locationId,int unitId,int transactionId)
        {
            List<SqlParameter> parameter = new List<SqlParameter>
            {
                new SqlParameter("ChargeBoxId", SqlDbType.NVarChar, 50){ Value = chargeBoxId },
                new SqlParameter("ConnectorId", SqlDbType.TinyInt) { Value = connectorId },
                new SqlParameter("Value", SqlDbType.Decimal) { Value = value, Precision = 18, Scale = 8 },
                new SqlParameter("CreatedOn", SqlDbType.DateTime) { Value = createdOn },
                new SqlParameter("ContextId", SqlDbType.Int) { Value = contextId },
                new SqlParameter("FormatId", SqlDbType.Int) { Value = formatId },
                new SqlParameter("MeasurandId", SqlDbType.Int) { Value = measurandId },
                new SqlParameter("PhaseId", SqlDbType.Int) { Value = phaseId },
                new SqlParameter("LocationId", SqlDbType.Int) { Value = locationId },
                new SqlParameter("UnitId", SqlDbType.Int) { Value = unitId },
                new SqlParameter("TransactionId", SqlDbType.Int) { Value = transactionId },
            };
            sqlParameters.AddRange(parameter);
        }
    }
}
