RemovePortUseCase.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. using RackPeek.Domain.Resources.Connections;
  5. using RackPeek.Domain.Resources.Servers;
  6. namespace RackPeek.Domain.UseCases.Ports;
  7. public interface IRemovePortUseCase<T> : IResourceUseCase<T>
  8. where T : Resource {
  9. Task ExecuteAsync(string name, int index);
  10. }
  11. public class RemovePortUseCase<T>(IResourceCollection repository)
  12. : IRemovePortUseCase<T> where T : Resource {
  13. public async Task ExecuteAsync(string name, int index) {
  14. name = Normalize.HardwareName(name);
  15. ThrowIfInvalid.ResourceName(name);
  16. T resource = await repository.GetByNameAsync<T>(name)
  17. ?? throw new NotFoundException($"Resource '{name}' not found.");
  18. if (resource is not IPortResource pr)
  19. throw new NotFoundException($"Resource '{name}' not found.");
  20. if (pr.Ports == null || index < 0 || index >= pr.Ports.Count)
  21. throw new NotFoundException($"Port index {index} not found on '{name}'.");
  22. IReadOnlyList<Connection> connections =
  23. await repository.GetConnectionsForResourceAsync(name);
  24. var toRemove = new List<Connection>();
  25. var toAdd = new List<Connection>();
  26. foreach (Connection connection in connections) {
  27. var changed = false;
  28. PortReference a = connection.A;
  29. PortReference b = connection.B;
  30. // handle A side
  31. if (a.Resource.Equals(name, StringComparison.OrdinalIgnoreCase)) {
  32. if (a.PortGroup == index) {
  33. toRemove.Add(connection);
  34. continue;
  35. }
  36. if (a.PortGroup > index) {
  37. a = new PortReference {
  38. Resource = a.Resource,
  39. PortGroup = a.PortGroup - 1,
  40. PortIndex = a.PortIndex
  41. };
  42. changed = true;
  43. }
  44. }
  45. // handle B side
  46. if (b.Resource.Equals(name, StringComparison.OrdinalIgnoreCase)) {
  47. if (b.PortGroup == index) {
  48. toRemove.Add(connection);
  49. continue;
  50. }
  51. if (b.PortGroup > index) {
  52. b = new PortReference {
  53. Resource = b.Resource,
  54. PortGroup = b.PortGroup - 1,
  55. PortIndex = b.PortIndex
  56. };
  57. changed = true;
  58. }
  59. }
  60. if (changed) {
  61. toRemove.Add(connection);
  62. toAdd.Add(new Connection {
  63. A = a,
  64. B = b,
  65. Label = connection.Label,
  66. Notes = connection.Notes
  67. });
  68. }
  69. }
  70. foreach (Connection connection in toRemove)
  71. await repository.RemoveConnectionAsync(connection);
  72. foreach (Connection connection in toAdd)
  73. await repository.AddConnectionAsync(connection);
  74. pr.Ports.RemoveAt(index);
  75. await repository.UpdateAsync(resource);
  76. }
  77. }