/*****************************************************************************
* smsub Server Manager Subprocess
* Copyright (C) 2020 Syping
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* This software is provided as-is, no warranties are given to you, we are not
* responsible for anything with use of the software, you are self responsible.
*****************************************************************************/

#include "SMSubServer.h"
#include "smsub.h"

SMSubServer::SMSubServer(const QString &socket)
{
    listen(socket);
}

void SMSubServer::incomingConnection(quintptr socketDescriptor)
{
    QLocalSocket *localSocket = new QLocalSocket();
    localSocket->setSocketDescriptor(socketDescriptor);
    QObject::connect(localSocket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    QObject::connect(localSocket, SIGNAL(disconnected()), this, SLOT(deleteSocket()));
    sockets << localSocket;
}

void SMSubServer::readyRead()
{
    QLocalSocket *socket = (QLocalSocket*)sender();
    while (socket->canReadLine()) {
        const QByteArray readData = socket->readLine().trimmed();
        if (readData.startsWith("+log")) {
            socket->setProperty("ReceiveLog", true);
        }
        else if (readData.startsWith("-log")) {
            socket->setProperty("ReceiveLog", false);
        }
        else if (readData.startsWith("kill")) {
            emit killRequested();
        }
        else if (readData.startsWith("stop")) {
            emit stopRequested();
        }
        else if (readData.startsWith("wl")) {
            emit inputWritten(readData.mid(3) + '\n');
        }
        else if (readData.startsWith("w")) {
            emit inputWritten(readData.mid(2));
        }
    }
}

void SMSubServer::deleteSocket()
{
    QLocalSocket *socket = (QLocalSocket*)sender();
    sockets.removeAll(socket);
    socket->deleteLater();
}

void SMSubServer::writeOutput(const QByteArray &output)
{
    QVector<QLocalSocket*>::const_iterator it = sockets.constBegin();
    QVector<QLocalSocket*>::const_iterator end = sockets.constEnd();
    while (it != end) {
        const QVariant variant = (*it)->property("ReceiveLog");
        if (unlikely(variant.type() == QVariant::Bool)) {
            bool receiveLog = variant.toBool();
            if (likely(receiveLog)) {
                (*it)->write(output);
            }
        }
        it++;
    }
}