using System;
using System.Collections.Generic;
using JD.Interfaces.Remoting;
namespace JD.Remoting.Details
{
///
/// Allows to register a Query and to have a callback when the data is ready.
///
public class QueryDictionary
{
private readonly List m_queries = new List();
public bool Handle(IMessage message)
{
var query = DequeueQuery(message.CommandName);
if (query != null)
{
query.HandleResultAction(message.Content.ConvertToRead());
return true;
}
return false;
}
public void Register(string commandName, Action handleQuery)
{
m_queries.Add(new PendingQuery(commandName, handleQuery));
}
private PendingQuery DequeueQuery(string commandName)
{
lock (m_queries)
{
for (int i = 0; i < m_queries.Count; i++)
{
if (m_queries[i].CommandName == commandName)
{
var query = m_queries[i];
m_queries.RemoveAt(i);
return query;
}
}
}
return null;
}
private class PendingQuery
{
public string CommandName { get; private set; }
public Action HandleResultAction { get; private set; }
public PendingQuery(string commandName, Action handleResultAction)
{
CommandName = commandName;
HandleResultAction = handleResultAction;
}
}
}
}