#include "databasethread.h"

#define HostName "172.17.35.51"
#define HostPort 3306
#define UserName "usky"
#define PassWord "Yt#75Usky"
#define DatabaseName "usky-park"

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

    db = QSqlDatabase::addDatabase("QMYSQL","write_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::appendAlarm(QString sql)
{
    alarmList.append(sql);
}


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

void DatabaseThread::run()
{
    keep = true;
    while (keep) {

        if(!db.open()){
            emit dbdata_log(QString("[%1] agGeneratorProcess DatabaseThread db open failed").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")));
        }else{
            if(sqlList.length()>0){
                while (sqlList.length()>0) {

                    emit dbdata_log(QString("[%1] agGeneratorProcess sql %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(sqlList.first()));

                    db.exec(sqlList.first());

                    sqlList.removeFirst();
                    usleep(1000);
                }
            }
            if(alarmList.length()>0){
                while (alarmList.length()>0) {
                    db.exec(alarmList.first());

                    emit dbdata_log(QString("[%1] agGeneratorProcess alarm sql %2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss.zzz")).arg(alarmList.first()));

                    alarmList.removeFirst();
                    usleep(1000);
                }
            }
        }
        usleep(50000);
    }


}











