/**
 *
 * We received a disconnect signal. Lets cleanup the connection in question
 *
 * @param args The arguments passed from the database
 * @return void
 */
void DatabaseConnectionManager::disconnected(const VariantVector &args)
{
    DatabaseConnection *connection;
    std::string uuid;
    Variant uid = args.data()[0];

    uuid = uid.toString();

    // Find connection
    connection = disconnectingConnections[uuid];

    // Stop running
    connection->stop();

    // Wait for the connection to finish
    while (!connection->isFinished()) {

        // Process any pending events
        Application::getInstance()->processEvents();

        // Sleep for 30ms.
        usleep(30 * 1000);
    }

    // Remove from collection
    disconnectingConnections.erase(uuid);

    // Free memory
    if (connection != mainConnection) {
        delete connection;
    }
}
/**
 *
 * Destroys this connection manager
 *
 * @return void
 */
DatabaseConnectionManager::~DatabaseConnectionManager()
{
    DatabaseConnection *connection;
    bool waiting = true;

    while (waiting) {

        // Our default state is not waiting
        waiting = false;

        Connections connections(this->connections);
        for (Connections::const_iterator it = connections.begin();
                it != connections.end(); ++it) {

            connection = it->first;

            if (connection->isStopping()) {

                // Wait for the connection to finish
                connection->join();

                // Remove from collection
                this->connections.erase(connection);

                // Free memory
                if (connection != mainConnection) {
                    delete connection;
                }
            } else {

                // Ask the connection to stop running
                connection->stop(false);

                // This connection may not be finished yet
                waiting = true;
            }
        }
    }

    delete this->mainConnection;

    #ifdef TRACK_POINTERS
    rDebug << "DatabaseConnectionManager::destroy" << this;
    #endif
}