/*
 * synergy -- mouse and keyboard sharing utility
 * Copyright (C) 2012-2016 Symless Ltd.
 * Copyright (C) 2004 Chris Schoeneman
 * 
 * This package is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * found in the file LICENSE that should have accompanied this file.
 * 
 * This package is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "server/ClientListener.h"

#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "core/PacketStreamFilter.h"
#include "net/IDataSocket.h"
#include "net/IListenSocket.h"
#include "net/ISocketFactory.h"
#include "net/XSocket.h"
#include "server/ClientProxy.h"
#include "server/ClientProxyUnknown.h"

//
// ClientListener
//

ClientListener::ClientListener(const NetworkAddress& address,
                ISocketFactory* socketFactory,
                IEventQueue* events) :
    m_socketFactory(socketFactory),
    m_server(nullptr),
    m_events(events)
{
    assert(m_socketFactory != NULL);

    try {
        m_listen = m_socketFactory->createListen();

        // setup event handler
        m_events->adoptHandler(m_events->forIListenSocket().connecting(),
                    m_listen,
                    new TMethodEventJob<ClientListener>(this,
                            &ClientListener::handleClientConnecting));
        
        // bind listen address
        LOG((CLOG_DEBUG1 "binding listen socket"));
        m_listen->bind(address);
    }
    catch (XSocketAddressInUse&) {
        cleanupListenSocket();
        delete m_socketFactory;
        throw;
    }
    catch (XBase&) {
        cleanupListenSocket();
        delete m_socketFactory;
        throw;
    }
    LOG((CLOG_DEBUG1 "listening for clients"));
}

ClientListener::~ClientListener()
{
    LOG((CLOG_DEBUG1 "stop listening for clients"));

    // discard already connected clients
    for (auto client : m_newClients) {
        m_events->removeHandler(
                            m_events->forClientProxyUnknown().success(), client);
        m_events->removeHandler(
                            m_events->forClientProxyUnknown().failure(), client);
        m_events->removeHandler(
                            m_events->forClientProxy().disconnected(), client);
        delete client;
    }

    // discard waiting clients
    ClientProxy* client = getNextClient();
    while (client != nullptr) {
        delete client;
        client = getNextClient();
    }

    m_events->removeHandler(m_events->forIListenSocket().connecting(), m_listen);
    cleanupListenSocket();
    delete m_socketFactory;
}

void
ClientListener::setServer(Server* server)
{
    assert(server != NULL);
    m_server = server;
}

ClientProxy*
ClientListener::getNextClient()
{
    ClientProxy* client = nullptr;
    if (!m_waitingClients.empty()) {
        client = m_waitingClients.front();
        m_waitingClients.pop_front();
        m_events->removeHandler(m_events->forClientProxy().disconnected(), client);
    }
    return client;
}

void
ClientListener::handleClientConnecting(const Event& /*unused*/, void* /*unused*/)
{
    // accept client connection
    IDataSocket* socket = m_listen->accept();

    if (socket == nullptr) {
        return;
    }
    
    m_events->adoptHandler(m_events->forClientListener().accepted(),
                socket->getEventTarget(),
                new TMethodEventJob<ClientListener>(this,
                        &ClientListener::handleClientAccepted, socket));
    
    m_events->addEvent(Event(m_events->forClientListener().accepted(),
                            socket->getEventTarget()));
}

void
ClientListener::handleClientAccepted(const Event& /*unused*/, void* vsocket)
{
    LOG((CLOG_NOTE "accepted client connection"));

    auto* socket = static_cast<IDataSocket*>(vsocket);
    
    // filter socket messages, including a packetizing filter
    synergy::IStream* stream = new PacketStreamFilter(m_events, socket, true);
    assert(m_server != NULL);

    // create proxy for unknown client
    auto* client = new ClientProxyUnknown(stream, 30.0, m_server, m_events);

    m_newClients.insert(client);

    // watch for events from unknown client
    m_events->adoptHandler(m_events->forClientProxyUnknown().success(),
                client,
                new TMethodEventJob<ClientListener>(this,
                        &ClientListener::handleUnknownClient, client));
    m_events->adoptHandler(m_events->forClientProxyUnknown().failure(),
                client,
                new TMethodEventJob<ClientListener>(this,
                        &ClientListener::handleUnknownClient, client));
}

void
ClientListener::handleUnknownClient(const Event& /*unused*/, void* vclient)
{
    auto* unknownClient =
        static_cast<ClientProxyUnknown*>(vclient);

    // we should have the client in our new client list
    assert(m_newClients.count(unknownClient) == 1);

    // get the real client proxy and install it
    ClientProxy* client = unknownClient->orphanClientProxy();
    bool handshakeOk = true;
    if (client != nullptr) {
        // handshake was successful
        m_waitingClients.push_back(client);
        m_events->addEvent(Event(m_events->forClientListener().connected(),
                                 this));

        // watch for client to disconnect while it's in our queue
        m_events->adoptHandler(m_events->forClientProxy().disconnected(), client,
                            new TMethodEventJob<ClientListener>(this,
                                &ClientListener::handleClientDisconnected,
                                client));
    }
    else {
        handshakeOk = false;
    }

    // now finished with unknown client
    m_events->removeHandler(m_events->forClientProxyUnknown().success(), client);
    m_events->removeHandler(m_events->forClientProxyUnknown().failure(), client);
    m_newClients.erase(unknownClient);
    auto* streamFileter = dynamic_cast<PacketStreamFilter*>(unknownClient->getStream());
    IDataSocket* socket = nullptr;
    if (streamFileter != nullptr) {
        socket = dynamic_cast<IDataSocket*>(streamFileter->getStream());
    }

    delete unknownClient;
}

void
ClientListener::handleClientDisconnected(const Event& /*unused*/, void* vclient)
{
    auto* client = static_cast<ClientProxy*>(vclient);

    // find client in waiting clients queue
    for (auto i = m_waitingClients.begin(),
                            n = m_waitingClients.end(); i != n; ++i) {
        if (*i == client) {
            m_waitingClients.erase(i);
            m_events->removeHandler(m_events->forClientProxy().disconnected(),
                            client);
            delete client;
            break;
        }
    }
}

void
ClientListener::cleanupListenSocket()
{
    delete m_listen;
}
