#include "tcpserver1.h"
#include "boxdeviceshm.h"

TcpServer1::TcpServer1(QObject *parent) : QObject(parent)
{
    svr = new QTcpServer(this);
    connect(svr,SIGNAL(newConnection()),this,SLOT(new_incomming()));

    networkManager = new QNetworkAccessManager(this);
    connect(networkManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(finishedSlot(QNetworkReply *)));

}

void TcpServer1::start()
{
    if(!svr->listen(QHostAddress::Any,15226)){
        printf("tcpserver1 listen 15226 failed\n");
        exit(-1);
    }
    printf("tcpserver1 listen 15226 success\n");

}

void TcpServer1::finishedSlot(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError){
        QString data = QString::fromUtf8(reply->readAll());
        QString recmsg = QString("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\n\r\n%1").arg(data);
        so->write(recmsg.toUtf8());
        so->close();
    }

    reply->abort();
    reply->deleteLater();
}

void TcpServer1::new_incomming()
{
    so = svr->nextPendingConnection();
    connect(so,SIGNAL(readyRead()),this,SLOT(read_data()));
}

void TcpServer1::read_data()
{
    QString str = QString::fromUtf8(so->readAll());
    int begin = str.indexOf("{",0);
    int len = str.length();
    QString data = str.mid(begin,len-begin+1);
    QString dt = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    emit tcp_log(QString("[%1] tcpserver1 data %2").arg(dt).arg(data));
    QByteArray ba = data.toLocal8Bit();
    ba = QString::fromLocal8Bit(ba).toUtf8();
    QJsonParseError parse_error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&parse_error);
    printf("parse_error.error %d\n",parse_error.error);
    if(parse_error.error == QJsonParseError::NoError){
        QJsonObject doc_obj = jsonDoc.object();
        QJsonValue param_val = doc_obj.value("params");
        QJsonObject param_obj = param_val.toObject();
        QString deviceId = param_obj.value("device_id").toString();
        int action = param_obj.value("action").toInt();
        QString command = param_obj.value("command").toString();
        int speed = param_obj.value("speed").toInt();
        int presetIndex = param_obj.value("presetIndex").toInt();
        for(int i=0;i<1024;i++){
            if(boxDeviceShm->device[i].Enabled == 0x01){
                if(deviceId.compare(QString(boxDeviceShm->device[i].device_id))==0){
                    QNetworkRequest *req = new QNetworkRequest();
                    req->setUrl(QUrl("https://172.17.200.250:443/artemis/api/video/v1/ptzs/controlling"));
                    req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
                    req->setRawHeader("Accept","*/*");
                    req->setRawHeader("Connection","keep-alive");
                    req->setRawHeader("Cache-Control"," no-cache");
                    req->setRawHeader("X-Ca-Key","27997984");
                    req->setRawHeader("X-Ca-Signature","C/1aEVkfDZhGXuCH64tGv1vfySvDMTSMkqKd5PXgOM8=");
                    req->setRawHeader("X-Ca-Signature-Headers","x-ca-key");
                    config = req->sslConfiguration();
                    config.setPeerVerifyMode(QSslSocket::VerifyNone);
                    config.setProtocol(QSsl::TlsV1_0OrLater);
                    req->setSslConfiguration(config);
                    QString postdata = QString("{\"cameraIndexCode\": \"%1\",\"action\": %2,\"command\":\"%3\",\"speed\":%4,\"presetIndex\":%5}")
                            .arg(boxDeviceShm->device[i].device_code).arg(action).arg(command).arg(speed).arg(presetIndex);
                    req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
                    networkManager->post(*req,postdata.toUtf8());
                    break;
                }
            }
        }

    }

}












