using System;
using System.Collections.Generic;


namespace AIRuntime.Runtime.Agents
{
    /// <summary>
    /// Stores available agent definitions.
    /// </summary>
    public sealed class AgentRegistry
    {
        private readonly Dictionary<string, AgentDefinition> _agents =
            new Dictionary<string, AgentDefinition>();


        public int Count
        {
            get
            {
                return _agents.Count;
            }
        }


        public void Register(
            AgentDefinition agent)
        {
            if (agent == null)
            {
                throw new ArgumentNullException(
                    nameof(agent));
            }


            if (_agents.ContainsKey(
                    agent.Id))
            {
                throw new InvalidOperationException(
                    $"Agent '{agent.Id}' is already registered.");
            }


            _agents.Add(
                agent.Id,
                agent);
        }


        public bool Remove(
            string agentId)
        {
            if (string.IsNullOrWhiteSpace(agentId))
                return false;


            return _agents.Remove(
                agentId);
        }


        public bool Contains(
            string agentId)
        {
            return
                !string.IsNullOrWhiteSpace(agentId)
                &&
                _agents.ContainsKey(agentId);
        }


        public AgentDefinition Get(
            string agentId)
        {
            if (!_agents.TryGetValue(
                    agentId,
                    out AgentDefinition agent))
            {
                throw new KeyNotFoundException(
                    $"Agent '{agentId}' is not registered.");
            }


            return agent;
        }


        public IReadOnlyList<AgentDefinition> GetAll()
        {
            return new List<AgentDefinition>(
                _agents.Values);
        }
    }
}
