DescribeSwitchUseCase.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources.SubResources;
  4. namespace RackPeek.Domain.Resources.Switches;
  5. public record SwitchDescription(
  6. string Name,
  7. string? Model,
  8. bool? Managed,
  9. bool? Poe,
  10. int TotalPorts,
  11. double TotalSpeedGb,
  12. string PortSummary,
  13. Dictionary<string, string> Labels
  14. );
  15. public class DescribeSwitchUseCase(IResourceCollection repository) : IUseCase {
  16. public async Task<SwitchDescription> ExecuteAsync(string name) {
  17. name = Normalize.HardwareName(name);
  18. ThrowIfInvalid.ResourceName(name);
  19. var switchResource = await repository.GetByNameAsync(name) as Switch;
  20. if (switchResource == null)
  21. throw new NotFoundException($"Switch '{name}' not found.");
  22. // If no ports exist, return defaults
  23. List<Port> ports = switchResource.Ports ?? new List<Port>();
  24. // Total ports count
  25. var totalPorts = ports.Sum(p => p.Count ?? 0);
  26. // Total speed (sum of each port speed * count)
  27. var totalSpeedGb = ports.Sum(p => (p.Speed ?? 0) * (p.Count ?? 0));
  28. // Build a port summary string
  29. IEnumerable<string> portGroups = ports
  30. .GroupBy(p => p.Type ?? "Unknown")
  31. .Select(g => {
  32. var count = g.Sum(x => x.Count ?? 0);
  33. var speed = g.Sum(x => (x.Speed ?? 0) * (x.Count ?? 0));
  34. return $"{g.Key}: {count} ports ({speed} Gb total)";
  35. });
  36. var portSummary = string.Join(", ", portGroups);
  37. return new SwitchDescription(
  38. switchResource.Name,
  39. switchResource.Model,
  40. switchResource.Managed,
  41. switchResource.Poe,
  42. totalPorts,
  43. totalSpeedGb,
  44. portSummary,
  45. switchResource.Labels
  46. );
  47. }
  48. }