using ReactorMaintenance.Simulation;

namespace ReactorMaintenance.Simulation.Effects;

public sealed class FireAndElectricalHazardEffect : ISimulationEffect
{
    public CellState Apply(CellState cell)
    {
        var hazards = cell.Hazards;
        if (hazards.CoolantPooling >= Balancing.Current.ElectrifiedCoolantPoolingThreshold && cell.Powered)
            hazards = hazards with { ElectricalCharge = hazards.ElectricalCharge + Balancing.Current.ElectricalChargeIncrease };

        var hasFuel = hazards.FuelVapor >= Balancing.Current.FuelVaporFireThreshold || hazards.LiquidFuel >= Balancing.Current.LiquidFuelFireThreshold;
        var hasIgnition = hazards.Heat >= Balancing.Current.HeatIgnitionThreshold || hazards.ElectricalCharge >= Balancing.Current.ElectricalIgnitionThreshold || cell is { Prop: ECellProp.Generator, Powered: true };
        if ((hasFuel && hasIgnition) || hazards.Fire)
        {
            hazards = hazards with {
                Fire = hasFuel || hazards.Fire,
                Heat = hazards.Heat + Balancing.Current.FireHeatIncrease,
                Smoke = hazards.Smoke + Balancing.Current.FireSmokeIncrease,
                LiquidFuel = Math.Max(Balancing.Current.MinHazardValue, hazards.LiquidFuel - Balancing.Current.FireLiquidFuelConsumption),
                FuelVapor = Math.Max(Balancing.Current.MinHazardValue, hazards.FuelVapor - Balancing.Current.FireFuelVaporConsumption)
            };
        }
        else if (hazards.Smoke > Balancing.Current.MinHazardValue)
            hazards = hazards with { Smoke = hazards.Smoke - Balancing.Current.SmokeDecay };

        return cell with { Hazards = hazards.Clamp() };
    }
}