#include "tcpserver.h"
#include "../agVideoProcess/boxdeviceshm.h"

TcpServer::TcpServer(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 TcpServer::start()
{
    if(!svr->listen(QHostAddress::Any,15227)){
        printf("tcpserver listen 15227 failed\n");
        exit(-1);
    }
    printf("tcpserver listen 15227 success\n");
}

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

void TcpServer::finishedSlot(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError){
        QString str = QString::fromUtf8(reply->readAll());
        QJsonParseError parse_error;
        QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8(),&parse_error);
        if(parse_error.error==QJsonParseError::NoError){
            QJsonObject obj = doc.object();
            QString code = obj.value("code").toString();
            QString msg = obj.value("msg").toString();
            QString msgrec = QString("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nContent-type: text/plain\r\n\r\n{\"code\":\"%1\",\"msg\":\"%2\",\"data\":\"\"}").arg(code).arg(msg);
            so->write(msgrec.toUtf8());
            so->close();
        }
    }

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

void TcpServer::read_data()
{
    QString str = QString::fromUtf8(so->readAll());
    int begin = str.indexOf("{",0);
    int len = str.length();
    QString datetime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString data = str.mid(begin,len-begin+1);
    emit tcp_log(QString("[%1] video tcp data %2").arg(datetime).arg(data));
    QByteArray ba = data.toLocal8Bit();
    ba = QString::fromLocal8Bit(ba).toUtf8();

    QJsonParseError parse_error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(ba,&parse_error);
    printf("tcpserver parse_error %d\n",parse_error.error);
    if(parse_error.error == QJsonParseError::NoError){
        QJsonObject doc = jsonDoc.object();
        QJsonValue param_val = doc.value("params");
        QJsonObject param_obj = param_val.toObject();
        QString deviceId = param_obj.value("device_id").toString();
        int controlType = param_obj.value("controlType").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/acs/v1/door/doControl"));
                    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","azbiDyuW3AhipLvGYQQnU015ah2EVVofkBX19GRaZ1g=");
                    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("{\"doorIndexCodes\": [\"%1\"],\"controlType\": %2}")
                            .arg(boxDeviceShm->device[i].device_code).arg(controlType);
                    req->setRawHeader("Content_Length",QString("%1").arg(postdata.length()).toUtf8());
                    networkManager->post(*req,postdata.toUtf8());
                    break;
                }
            }
        }

    }


}








