/*****************************************************************************
* luaEngine Lua Engine for Qt
* Copyright (C) 2020 Syping
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/

#include "LuaEngineNetwork.h"
#include <QAbstractSocket>
#include <QLocalSocket>

void LuaEngineNetwork::pushClass(lua_State *L_p)
{
    // Local Socket
    pushFunction(L_p, "createLocalSocket", createLocalSocket);

    // Socket
    pushFunction(L_p, "socketConnect", socketConnect);
}

void LuaEngineNetwork::pushClass(LuaEngine *luaEngine)
{
    pushClass(luaEngine->luaState());
}

int LuaEngineNetwork::createLocalSocket(lua_State *L_p)
{
    QObject *parent = nullptr;
    if (getArgumentCount(L_p) >= 1) {
        void *pointer = getPointer(L_p, 1);
        if (pointer != NULL) {
            parent = (QObject*)pointer;
        }
    }
    QLocalSocket *localSocket = new QLocalSocket(parent);
    localSocket->setObjectName(nameForPointer(localSocket));
    pushPointer(L_p, localSocket);
    return 1;
}

int LuaEngineNetwork::socketConnect(lua_State *L_p)
{
    if (getArgumentCount(L_p) >= 2) {
        void *pointer = getPointer(L_p, 1);
        if (pointer != NULL) {
            if (((QObject*)pointer)->inherits("QLocalSocket")) {
                ((QLocalSocket*)pointer)->connectToServer(getVariant(L_p, 2).toString(), QIODevice::ReadWrite);
            }
            else if (((QObject*)pointer)->inherits("QAbstractSocket")) {
                const QStringList remoteIPPort = getVariant(L_p, 2).toString().split(":");
                if (remoteIPPort.length() >= 2) {
                    ((QAbstractSocket*)pointer)->connectToHost(remoteIPPort.at(0), remoteIPPort.at(1).toUShort(), QIODevice::ReadWrite);
                }
            }
        }
    }
    return 0;
}

QString LuaEngineNetwork::nameForPointer(void *pointer)
{
    QString nameStorage;
    QTextStream(&nameStorage) << "LuaEngineNetwork" << pointer;
    return nameStorage;
}