/*!
  \file
  \brief 接続の受付

  \author Satofumi KAMIMURA

  $Id: TcpipAccepter.cpp 1817 2010-05-09 09:04:32Z satofumi $
*/

#include "TcpipAccepter.h"
#include "TcpipSocket.h"
#include <QTcpServer>
#include <QHostAddress>
#include <string>

using namespace qrk;
using namespace std;


struct TcpipAccepter::pImpl
{
    string error_message_;
    string server_name_;
    QTcpServer tcp_server_;


    pImpl(void) : error_message_("no error."), server_name_("unknown")
    {
    }


    bool activate(long port)
    {
        return tcp_server_.listen(QHostAddress::Any, port);
    }


    void deactivate(void)
    {
        tcp_server_.close();
    }


    TcpipSocket* accept(int timeout)
    {
        if (tcp_server_.hasPendingConnections()) {
            return new TcpipSocket(tcp_server_.nextPendingConnection());

        } else if (tcp_server_.waitForNewConnection(timeout)) {
            return new TcpipSocket(tcp_server_.nextPendingConnection());
        }
        return NULL;
    }
};


TcpipAccepter::TcpipAccepter(void) : pimpl(new pImpl)
{
}


TcpipAccepter::~TcpipAccepter(void)
{
}


const char* TcpipAccepter::what(void) const
{
    return pimpl->error_message_.c_str();
}


bool TcpipAccepter::activate(long port)
{
    return pimpl->activate(port);
}


void TcpipAccepter::deactivate(void)
{
    pimpl->deactivate();
}


TcpipSocket* TcpipAccepter::accept(int timeout)
{
    return pimpl->accept(timeout);
}


const char* TcpipAccepter::name(void)
{
    return pimpl->server_name_.c_str();
}
