using System.Collections.Concurrent;
using System.Collections.Generic;
using BattSim.Models;

namespace BattSim.Services
{
    public static class BatterySimulator
    {
        public static EnergyData[] SimulateBattery(EnergyData[] energyData, double batteryCapacity, double efficiency)
        {
            var results = new List<EnergyData>();
            double batteryCharge = 0;
            
            foreach (var e in energyData)
            {
                var simulatedBatteryEnergyData = new EnergyData(e);
                // Simulate charging the battery based on production
                double excessProduction = batteryCharge + e.Production - batteryCapacity;
                batteryCharge = double.Min(batteryCharge + e.Production, batteryCapacity);
                simulatedBatteryEnergyData.Production = double.Max(excessProduction, 0);
                
                // Simulate discharging the battery based on consumption
                double availableEnergy = batteryCharge * efficiency;
                double deficit = e.Consumption - availableEnergy;
                double energyDrawn = Math.Min(e.Consumption, availableEnergy);
                batteryCharge = batteryCharge - (energyDrawn / efficiency); // Adjust for loss
                simulatedBatteryEnergyData.Consumption = Math.Max(deficit, 0);

                // Register the current charge
                simulatedBatteryEnergyData.BatteryCharge = batteryCharge;
                results.Add(simulatedBatteryEnergyData);
            }
            
            return results.ToArray();
        }
    }
}