Files
FoodFactory/src/Equipment/BeltPortHost.cs
2026-05-12 09:53:30 -04:00

50 lines
1.3 KiB
C#

namespace FoodFactory.Equipment;
using System;
using System.Collections.Generic;
using FoodFactory.Items;
public interface IBeltPortHost
{
IBeltItemInsertLogic ResolveInsertLogic(IBeltPort port);
}
public class BeltPortHost : IBeltPortHost
{
private readonly List<(Func<IBeltPort, bool> match, Func<IBeltItemInsertLogic> factory)> _bindings
= new();
public BeltPortHost Bind(
Func<IBeltPort, bool> match,
Func<IBeltItemInsertLogic> factory)
{
_bindings.Add((match, factory));
return this;
}
private HashSet<IBeltPort> _ports = [];
public IBeltItemInsertLogic? Default;
/// <summary>
/// Resolve the insert logic for a port. If no matching bind exists then the default is returned if supplied. Other wise throws an Exception.
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public IBeltItemInsertLogic ResolveInsertLogic(IBeltPort port)
{
_ports.Add(port);
foreach (var (match, factory) in _bindings)
{
if (match(port))
{
return factory();
}
}
if (Default is null)
{
throw new Exception($"{nameof(port)} does not have any binding attached that accepts it.");
}
return Default;
}
public IEnumerable<IBeltPort> GetPorts() => _ports;
}