/* $Header: https://svn.mpia.de/gulli/TwiceAsNice/branch/unstable/ln/ltcs/test/LbtoIIFSimulator/LbtoIIFArbitrator.cc 14502 2017-07-17 08:46:15Z mathar $
*/

#include <LbtoIIFArbitrator.h>
#include <iostream>

/*!***********************************
* @brief Constructor
*/
lbto::Arbitrator::Arbitrator()
{
}

/*!**************************
* Destructor. Frees all the resources.
*/
lbto::Arbitrator::~Arbitrator()
{
}

/*!***********************
* @brief Remove the key and destroy the corresponding IIF instance.
* @param _proxyName the proxy name.
* @return true/false success or fail
*/
bool lbto::Arbitrator::DeRegister(const std::string _proxyName)
{
    IceUtil::LockT<IceUtil::RecMutex> guard(__connMutex);
    if (!(m_map.empty()) && (m_map.find(_proxyName) != m_map.end()))
    {
        m_map.erase(_proxyName);
        return true;
    }
    return false;
}

/*!******************************
* @brief Tell if the proxy already exist on the map.
* @param _proxyName the proxy name.
*/
bool lbto::Arbitrator::ProxyExist(const std::string _proxyName)
{
    IceUtil::LockT<IceUtil::RecMutex> guard(__connMutex);
    if ((m_map.empty()) || (m_map.find(_proxyName) == m_map.end()))
        return false;

    return true;
}

/*!*************************
* @brief Get the IIFServerPtr object mapped to the passed proxy name.
* @param _proxyName the proxy name to be created or searched for.
* @param _comm the Ice communicator pointer
* @return  the IIFServerPtr object mapped to the passed proxy name
*/
lbto::IIFServerPtr lbto::Arbitrator::getIIFServer(const std::string _proxyName,
                                                  Ice::CommunicatorPtr _comm)
{
    Ice::Print info(_comm->getLogger());
    IceUtil::LockT<IceUtil::RecMutex> guard(__connMutex);
    if ((m_map.empty()) || (m_map.find(_proxyName) == m_map.end()))
    {
        /* could not find it, so generate a new one.
        */
        m_map[_proxyName] = new lbto::IIFServerI();
        info << _proxyName << ":Registered proxy -- " << "Map size= "
                << (int) m_map.size();
        info.flush();
    }
    return m_map[_proxyName];
}
