#include "clientbase.h"

ClientBase::ClientBase(QObject *parent) :
    QObject(parent)
{
}


ClientBase::~ClientBase()
{
    closeConnection();
    delete m_socket;
}


void ClientBase::closeConnection()
{
    m_socket->disconnectFromHost();
}


QString ClientBase::getStatus()
{
    QString s;
    switch (m_socket->state())
    {
    case QAbstractSocket::UnconnectedState :
        s = trUtf8("not connected");
        break;
    case QAbstractSocket::HostLookupState :
        s = trUtf8("loking for server...");
        break;
    case QAbstractSocket::ConnectingState :
        s = trUtf8("connecting...");
        break;
    case QAbstractSocket::ConnectedState :
        s = trUtf8("connected!");
        break;
    case QAbstractSocket::ClosingState :
        s = trUtf8("disconnecting....");
        break;
    default:
        s = trUtf8("error");
    }
    s += trUtf8(" to %1:%2").arg(m_socket->peerAddress().toString()).arg(m_socket->peerPort());
    return s;
}


void ClientBase::send(const QByteArray &ba)
{
    m_socket->write(ba);
}


void ClientBase::readData()
{
    QByteArray ba = m_socket->readAll();
    if (!ba.isEmpty()) emit receive(ba);

}

void ClientBase::Disconnection()
{
    emit disconnected();
}
