using System.Collections;

namespace RobotNet.WebApp.Maps.Models;

public class MapElementModel : IEnumerable<ElementModel>
{
    private readonly Dictionary<Guid, ElementModel> dicElements = [];
    public IEnumerator<ElementModel> GetEnumerator() => dicElements.Values.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    public bool TryGetValue(Guid id, out ElementModel? value) => dicElements.TryGetValue(id, out value);
    public bool ContainsKey(Guid key) => dicElements.ContainsKey(key);

    public event Action? Changed;

    public void Add(ElementModel element)
    {
        if (dicElements.ContainsKey(element.Id)) return;

        dicElements.Add(element.Id, element);
        Changed?.Invoke();
    }

    public void ReplaceAll(IEnumerable<ElementModel> elements)
    {
        foreach (var robot in dicElements.Values)
        {
            robot.Dispose();
        }
        dicElements.Clear();

        foreach (var element in elements)
        {
            dicElements.Add(element.Id, element);
        }
        Changed?.Invoke();
    }

    public void Remove(ElementModel element)
    {
        if (!dicElements.ContainsKey(element.Id)) return;
        element.Dispose();
        dicElements.Remove(element.Id);
        Changed?.Invoke();
    }
}
