using Framework.Entities;
using Framework.Sharing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Framework.InteractionSystem
{
    /// <summary>
    /// Mediates communication between <see cref="Interactable"/> objects by broadcasting
    /// actions between them. Only subscribed listeners to a specific action type will
    /// receive the action.
    /// </summary>
    public class ActionMediator : Mediator<Actionlike, Interactable>
    {
        /// <summary>
        /// Broadcasts the specified action to all subscribers registered to that 
        /// action type.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <returns></returns>
        public override bool Broadcast(Actionlike action)
        {
            int responseCount = 0;
            if (this.messageMap.ContainsKey(action.GetType()))
            {
                for (int i = 0; i < this.messageMap[action.GetType()].Count; i++)
                {
                    if (this.messageMap[action.GetType()][i] == null)
                    {
                        this.messageMap[action.GetType()].RemoveAt(i);
                        break;
                    }
                    if (this.messageMap[action.GetType()][i].Receive(action))
                    {
                        responseCount++;
                    }
                }
            }
            return responseCount > 0;
        }
    }
}
