//
// C++ Implementation: simplelocalsocket
//
// Description:
//
//
// Author: Oleksandr Shneyder <o.shneyder@phoca-gmbh.de>, (C) 2006-2018
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "simplelocalsocket.h"
#include "sharetray.h"
#include <QLocalSocket>
#include <QTimer>

SimpleLocalSocket::SimpleLocalSocket(ShareTray* obj, QLocalSocket* soc,
                                     QObject *parent)
        : QObject(parent)
{
    socket=soc;
    trayApp=obj;
    if ( socket )
    {
        connect ( socket,SIGNAL ( readyRead() ),this,
                  SLOT ( slotReadFromSocket() ) );
    }
}


SimpleLocalSocket::~SimpleLocalSocket()
{
    if (socket && trayApp->acceptConnections())
    {
         socket->close();
         delete socket;
    }
}

void SimpleLocalSocket::slotReadFromSocket()
{
    char buffer[512];
    int read=socket->read ( buffer,511 );
    if ( read<=0 )
    {
        return;
    }
    buffer[read]=0;
    QString answer=trayApp->getSocketAnswer(buffer);
    if (!socket)
        return;
    if (socket->isValid() &&
            socket->state()==QLocalSocket::ConnectedState&&
            socket->openMode()!=QIODevice::NotOpen)
    {
        socket->write(answer.toLatin1().data(),
                      answer.toLatin1().length());
        QTimer::singleShot ( 10000, this, SLOT ( closeSocket() ) );
    }
}

void SimpleLocalSocket::closeSocket()
{
    trayApp->closeSocket(this);
}
