using RobotNet.WebApp.Robots.Components.Monitoring.Element;
using System.Collections;

namespace RobotNet.WebApp.Robots.Components.Monitoring;

public class MapRobotModel : IEnumerable<RobotVisualizationModel>
{
    private readonly Dictionary<string, RobotVisualizationModel> dicRobots = [];
    public IEnumerator<RobotVisualizationModel> GetEnumerator() => dicRobots.Values.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

    public event Action? Changed;

    public void Add(RobotVisualizationModel robot)
    {
        if (dicRobots.ContainsKey(robot.RobotId)) return;

        dicRobots.Add(robot.RobotId, robot);
        Changed?.Invoke();
    }

    public bool ContainsKey(string key) => dicRobots.ContainsKey(key);

    public void ReplaceAll(IEnumerable<RobotVisualizationModel> robots)
    {
        foreach (var robot in dicRobots.Values)
        {
            robot.Dispose();
        }
        dicRobots.Clear();

        foreach (var robot in robots)
        {
            robot.Update(robot.X, robot.Y, robot.Theta, robot.Loads);
            dicRobots.Add(robot.RobotId, robot);
        }
        Changed?.Invoke();
    }

    public void Remove(RobotVisualizationModel robot)
    {
        if (!dicRobots.ContainsKey(robot.RobotId)) return;
        robot.Dispose();
        dicRobots.Remove(robot.RobotId);
        Changed?.Invoke();
    }

    public bool TryGetValue(string id, out RobotVisualizationModel? value) => dicRobots.TryGetValue(id, out value);
}
