/*****************************************************************************
* 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 <QCoreApplication>
#include "SMSubServer.h"
#include "smsub.h"

SMSubServer::SMSubServer(const QString &socket)
{
    setSocketOptions(QLocalServer::UserAccessOption | QLocalServer::GroupAccessOption);
    listen(socket);
}

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

    // Initial open writing
    socket->write(QString("SMSub Version %1\n").arg(QCoreApplication::applicationVersion()).toUtf8());
}

void SMSubServer::readyRead()
{
    // Manage client input
    QLocalSocket *socket = (QLocalSocket*)sender();
    while (socket->canReadLine()) {
        const QByteArray readData = socket->readLine().trimmed();
        if (readData.startsWith("+dbg")) {
            socket->setProperty("ReceiveDbgMsg", true);
            socket->write("Debug messages enabled!\n");
        }
        else if (readData.startsWith("-dbg")) {
            socket->setProperty("ReceiveDbgMsg", false);
            socket->write("Debug messages disabled!\n");
        }
        else if (readData.startsWith("+log")) {
            socket->setProperty("ReceiveLog", true);
            debugOutput(socket, "Log output enabled!");
        }
        else if (readData.startsWith("-log")) {
            socket->setProperty("ReceiveLog", false);
            debugOutput(socket, "Log output disabled!");
        }
        else if (readData.startsWith("kill")) {
            emit killRequested();
            debugOutput(socket, "Killing server!");
        }
        else if (readData.startsWith("stop")) {
            emit stopRequested();
            debugOutput(socket, "Stopping server!");
        }
        else if (readData.startsWith("wl")) {
            const QByteArray writeData = readData.mid(3);
            emit inputWritten(writeData + '\n');
            debugOutput(socket, "Write line \"" + writeData + "\"!");
        }
        else if (readData.startsWith("w")) {
            const QByteArray writeData = readData.mid(2);
            emit inputWritten(writeData);
            debugOutput(socket, "Write \"" + writeData + "\"!");
        }
    }
}

void SMSubServer::deleteSocket()
{
    // Delete socket and remove from index
    QLocalSocket *socket = (QLocalSocket*)sender();
    sockets.removeAll(socket);
    socket->deleteLater();
}

void SMSubServer::debugOutput(QLocalSocket *socket, const QByteArray &message)
{
    // Only send debug messages when the client opted-in
    const QVariant variant = socket->property("ReceiveDbgMsg");
    if (unlikely(variant.type() == QVariant::Bool)) {
        bool receiveDbgMsg = variant.toBool();
        if (likely(receiveDbgMsg)) {
            socket->write(message + '\n');
        }
    }
}

void SMSubServer::writeOutput(const QByteArray &output)
{
    // Read process output when client opted-in for log
    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++;
    }
}