#include "server.h"

Server::Server(QObject *parent) :
    QObject(parent)
{
    m_server = new QTcpServer(this);
    next_conn_id = 1;
    connect(m_server,SIGNAL(newConnection()),this,SLOT(newConnection()));
}


QStringList Server::getIpList()
{
    QList<QHostAddress> list;
    list = QNetworkInterface::allAddresses();
    QStringList strl;
    foreach(QHostAddress adr,list) {
        if (adr.protocol() == QAbstractSocket::IPv4Protocol)
            strl.append(adr.toString());
    }
    return strl;
}


void Server::startServer(QHostAddress a)
{
    m_server->listen(a,44461);
}


void Server::stopServer()
{
    m_server->close();
    foreach (Connection * c, clients)
        c->closeConnection();
}

QString Server::getStatus()
{
    QString s;
    if (m_server->isListening())
        s = trUtf8("Running");
    else
        s = trUtf8("Stopped");
    s += "\n";
    foreach (Connection * c, clients)
        s += "\n" + c->getStatus();
    //s += trUtf8("Connections %1").arg(clients.size());
    return s;
}


void Server::send(const QByteArray &ba)
{
    foreach (Connection * c, clients)
        c->send(ba);
}


void Server::newConnection()
{
    clients.append(new Connection(next_conn_id, m_server->nextPendingConnection()));
    connect(clients.last(),SIGNAL(disconnected()),this,SLOT(connectionClosed()));
    connect(clients.last(),SIGNAL(receive(QByteArray)),this,SLOT(received(QByteArray)));
    next_conn_id++;
}


void Server::connectionClosed()
{
    sender()->deleteLater();
    clients.removeOne((qobject_cast<Connection*>(sender())));
}


void Server::received(QByteArray ba)
{
    emit receiveData(ba);
    send(ba);
}
