#include "databasethread.h"
#include "datashm.h"

//#define HostName  "47.98.201.187"
//#define HostPort 3306
//#define UserName "root"
//#define PassWord "Yt2018IoT"
//#define DatabaseName "jdxf"

#define HostName  "101.133.214.75"
#define HostPort 3306
#define UserName "usky"
#define PassWord "Yt#75Usky"
#define DatabaseName "usky-cloud"
#define sql_debug

extern bool firsttime;

DatabaseThread::DatabaseThread(QObject *parent) :
    QThread(parent)
{
    keep = false;
    hour = 255;
    sqlList.clear();

    db = QSqlDatabase::addDatabase("QMYSQL","dmpdata_db");
    db.setHostName(QString(HostName));
    db.setPort(HostPort);
    db.setUserName(QString(UserName));
    db.setPassword(QString(PassWord));
    db.setDatabaseName(QString(DatabaseName));
}

void DatabaseThread::appendSql(QString sql)
{
    sqlList.append(sql);
}

void DatabaseThread::check_devicelist()
{
    printf("database thread check_devicelist()\n");
    int nrow=0;
    QString sql = QString("select device_code,device_type from dmp_device");
    QSqlQuery qry = db.exec(sql);
    while(qry.next()){
        if(nrow>1023)
            break;
        datashm->devinfo[nrow].Enabled = 0x01;
        sprintf(datashm->devinfo[nrow].DeviceCode,"%s",qry.value(0).toString().toUtf8().data());
        datashm->devinfo[nrow].DeviceType = qry.value(1).toUInt();
//        printf("nrow: %d, device_code: %s, device_type: %d\n",nrow,qry.value(0).toString().toUtf8().data(),qry.value(1).toUInt());

        nrow++;
    }
    qry.clear();
    for(int i=nrow;i<1024;i++)
        datashm->devinfo[i].Enabled=0x00;
    hour=QTime::currentTime().hour();
}

void DatabaseThread::stop()
{
    keep = false;
}

void DatabaseThread::run()
{
    int w_count=0;
    keep = true;
    while(keep){
        if(w_count>9)
            exit(1);
        QTime nowTime = QTime::currentTime();
        if((sqlList.length()>0)||((nowTime.hour()!=hour)&&(nowTime.minute()>12))){
            if(!db.isOpen()){
                w_count++;
                db.open();
                //printf("w_count = %d\n",w_count);
            }else{
                w_count=0;
                if((nowTime.hour()!=hour)&&(nowTime.minute()>12)){
                    check_devicelist();
                }
                if(sqlList.length()>0){
                    db.exec(sqlList.first());
                    //printf("-----currenttime: %s sql = %s\n",(nowTime.toString("yyyy-MM-dd HH:mm:ss.zzz")).toUtf8().data(),(sqlList.first()).toUtf8().data());
    #ifdef sql_debug
                    emit SqlLog(QString("[ %1 sql ] ").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz"))+sqlList.first());
    #endif
                    sqlList.removeFirst();
                }else
                    db.close();
            }
        }
        usleep(10000);
    }
    if(db.isOpen())
        db.close();
}
