#include "ttsthreads.h"

ttsThreads::ttsThreads(QObject *parent, quint16 idx, QString ip, QString path, quint16 port) :
    QThread(parent)
{
    Idx = idx;
    DestIp = ip;
    DestPath = path;
    DestPort = port;
    DataList.clear();
}

void ttsThreads::appendData(QString data)
{
    QString Data = QString("POST %1 HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept: */*\r\nConnection: keep-alive\r\nCache-Control:  no-cache\r\nContent-Length: %2\r\nAccept-Encoding: gzip\r\nAccept-Language: zh-CN,en,*\r\nUser-Agent: Mozilla/5.0\r\nHost: %3:%4\r\n\r\n%5")
            .arg(DestPath).arg(data.length()).arg(DestIp).arg(DestPort).arg(data);
    DataList.append(Data);
}

void ttsThreads::stoptts()
{
    keepWorking = false;
}

void ttsThreads::ttslog(quint16 idx, QDateTime t, QString data, bool dirflag)
{
    if(dirflag)
        printf("[ %04d-%02d-%02d %02d:%02d:%02d >>> ] %s\n",
               t.date().year(),t.date().month(),t.date().day(),
               t.time().hour(),t.time().minute(),t.time().second(),
               data.toUtf8().data());
    else
        printf("[ %04d-%02d-%02d %02d:%02d:%02d <<< ] %s\n",
               t.date().year(),t.date().month(),t.date().day(),
               t.time().hour(),t.time().minute(),t.time().second(),
               data.toUtf8().data());
}

void ttsThreads::run()
{
    quint8 cur;
    for(int i=0;i<16;i++){
        so[i] = new QTcpSocket;
    }
    keepWorking = true;
    cur=0;
    while(keepWorking){
        if(DataList.length()>0){
            QString data = DataList.first();
            so[cur]->connectToHost(QHostAddress(DestIp),DestPort,QIODevice::ReadWrite);
            if(so[cur]->waitForConnected()){
                so[cur]->write(data.toUtf8());
                so[cur]->flush();
                ttslog(Idx,QDateTime::currentDateTime(),data,true);
                DataList.removeFirst();
                if(so[cur]->waitForReadyRead()){
                    QByteArray ret = so[cur]->readAll();
                    if(ret.length()>512)
                        ret = ret.mid(0,512);
                    ttslog(Idx,QDateTime::currentDateTime(),QString(ret),false);
                    so[cur]->close();
                }else{
                    ttslog(Idx,QDateTime::currentDateTime(),QString("timeout"),false);
                    so[cur]->abort();
                }
            }
            cur++;
            cur &= 0x0f;
        }
        usleep(100000);
    }
    for(int i=0;i<16;i++){
        if(so[i]->isOpen())
            so[i]->abort();
        so[i]->deleteLater();
    }
}
