using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Economy; using RailEnterprise.Core.Simulation.Systems; namespace RailEnterprise.Core.Simulation; /// Esecuzione dei comandi di gioco con validazione completa: un comando non valido non cambia nulla. public static class CommandProcessor { public static CommandResult Execute(World w, GameCommand command, WorldContext ctx) { CommandResult Result(CommandError error, string message) => new(command.Issuer, command.Seq, command.Type, error, message, ctx.Tick); CommandResult Reply(CommandError error, string message, params int[] created) => new(command.Issuer, command.Seq, command.Type, error, message, ctx.Tick) { Created = error == CommandError.None ? created : [] }; if (!command.Issuer.IsValid || command.Issuer.Value >= w.Companies.Count) return Result(CommandError.UnknownCompany, "Compagnia sconosciuta"); var company = w.Companies[command.Issuer.Value]; if (company.Merged) return Result(CommandError.NotAllowed, "La compagnia è stata incorporata"); if (company.Bankrupt) return Result(CommandError.Bankrupt, "La compagnia è in bancarotta"); if (company.IsPlayer && w.GameOver is not null) return Result(CommandError.NotAllowed, "Partita conclusa: si osserva il mondo senza poter dare comandi"); return command switch { TakeLoanCommand c => TakeLoan(w, company, c, Result), RepayLoanCommand c => RepayLoan(w, company, c, Result), SetIndustryPolicyCommand c => IndustryCommandHandlers.SetPolicy(w, company, c, Reply), BuyIndustryCommand c => IndustryCommandHandlers.BuyIndustry(w, company, c, Reply), OverhaulIndustryCommand c => IndustryCommandHandlers.Overhaul(w, company, c, Reply), UpgradeIndustryCommand c => IndustryCommandHandlers.Upgrade(w, company, c, Reply), IpoCommand c => CorporateCommandHandlers.Ipo(w, company, c, Reply), BuySharesCommand c => CorporateCommandHandlers.BuyShares(w, company, c, Reply), SellSharesCommand c => CorporateCommandHandlers.SellShares(w, company, c, Reply), PayDividendCommand c => CorporateCommandHandlers.PayDividend(w, company, c, Reply), LaunchBidCommand c => CorporateCommandHandlers.LaunchBid(w, company, c, Reply), RespondBidCommand c => CorporateCommandHandlers.RespondBid(w, company, c, Reply), MergeCompanyCommand c => CorporateCommandHandlers.MergeCompany(w, company, c, ctx, Reply), BuildTrackCommand c => RailCommandHandlers.BuildTrack(w, company, c, Reply), BuildStationCommand c => RailCommandHandlers.BuildStation(w, company, c, Reply), BuildDepotCommand c => RailCommandHandlers.BuildDepot(w, company, c, Reply), PlaceSignalCommand c => RailCommandHandlers.PlaceSignal(w, company, c, Reply), DemolishCommand c => RailCommandHandlers.Demolish(w, company, c, Reply), RenewTrackCommand c => RailCommandHandlers.RenewTrack(w, company, c, Reply), UpgradeTrackCommand c => RailCommandHandlers.UpgradeTrack(w, company, c, Reply), BuyVehicleCommand c => RailCommandHandlers.BuyVehicle(w, company, c, Reply), SellVehicleCommand c => RailCommandHandlers.SellVehicle(w, company, c, Reply), ComposeTrainCommand c => RailCommandHandlers.ComposeTrain(w, company, c, Reply), CreateLineCommand c => RailCommandHandlers.CreateLine(w, company, c, Reply), EditLineCommand c => RailCommandHandlers.EditLine(w, company, c, Reply), AssignTrainCommand c => RailCommandHandlers.AssignTrain(w, company, c, Reply), SendToDepotCommand c => RailCommandHandlers.SendToDepot(w, company, c, Reply), SetReserveCommand c => MaintenanceCommandHandlers.SetReserve(w, company, c, Reply), SetMaintenancePolicyCommand c => MaintenanceCommandHandlers.SetPolicy(w, company, c, Reply), ScheduleServiceCommand c => MaintenanceCommandHandlers.ScheduleService(w, company, c, ctx, Reply), OrderPartsCommand c => MaintenanceCommandHandlers.OrderParts(w, company, c, Reply), AcceptAgreementCommand c => MaintenanceCommandHandlers.AcceptAgreement(w, company, c, Reply), RejectAgreementCommand c => MaintenanceCommandHandlers.RejectAgreement(w, company, c, Reply), BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply), SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply), ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply), // le concessioni (F7) si rifiutano prima per il livello, poi perché non ancora disponibili; il testo // non promette che il livello basti BuyConcessionCommand when !Tiers.Unlocks(w, company).Concessions => Result(CommandError.TierLocked, Tiers.ConcessionsAvailable ? Tiers.LockedText(w, "Le concessioni", u => u.Concessions, plural: true) : Tiers.ConcessionsUnavailableText(w)), BuyConcessionCommand when !Tiers.ConcessionsAvailable => Result(CommandError.NotImplemented, "Le concessioni non sono ancora disponibili"), _ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"), }; } private static CommandResult TakeLoan(World w, Company company, TakeLoanCommand c, Func result) { if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido"); if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti"); var max = FinanceSystem.MaxLoan(w, company); if (company.Debt + c.Amount > max) return result(CommandError.CreditLimit, LoanLimitText(w, company, max)); var fb = w.Data.Balance.Finance; var loan = new Loan { Id = new LoanId(w.NextIds.Loan++), Principal = c.Amount, AnnualRate = FinanceSystem.LoanRate(w, company), TermMonths = fb.LoanTermMonths, Remaining = c.Amount, MonthsLeft = fb.LoanTermMonths, }; company.Loans.Add(loan); w.Money.Transfer(Account.External, Account.Of(company.Id), c.Amount, LedgerEntry.LoanTaken); return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni"); } /// /// Rifiuto per fido insufficiente: quanto resta disponibile e, se un livello successivo alza il /// fattore del fido, quale livello serve e a quanto porta il fido (ADR 0018). /// public static string LoanLimitText(World w, Company company, Money max) { string text = $"Fido insufficiente: disponibili {Money.Max(Money.Zero, max - company.Debt)} su {max}"; var current = Tiers.Def(w, company.Tier); var next = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Level > current.Level && t.Unlocks.MaxLoanFactor > current.Unlocks.MaxLoanFactor); return next is null ? text : $"{text}; il livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(company, next)}"; } private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func result) { var loan = company.Loans.FirstOrDefault(l => l.Id == c.Loan); if (loan is null) return result(CommandError.NotFound, "Prestito inesistente"); if (c.Amount.Cents <= 0) return result(CommandError.InvalidArgument, "Importo non valido"); var amount = Money.Min(c.Amount, loan.Remaining); if (company.Cash < amount) return result(CommandError.InsufficientFunds, "Cassa insufficiente"); w.Money.Transfer(Account.Of(company.Id), Account.External, amount, LedgerEntry.LoanRepaid); loan.Remaining -= amount; if (loan.Remaining.Cents <= 0) company.Loans.Remove(loan); return result(CommandError.None, $"Rimborsati {amount}"); } }