#include <QCoreApplication>
#include "boxshm.h"
#include "dogcore.h"
#include <QFile>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>

QSqlDatabase db;

AGBoxShm *agBoxShm;

void shm_init(){
    QSqlQuery qry;
    int nrow = 0;
    QString sql = QString("select device_code,device_id,device_type,product_code,device_gateway from yt_t_device");
    qry = db.exec(sql);
    while (qry.next()) {
        if(nrow > 1023)
            break;
        agBoxShm->device[nrow].Enabled = 0x01;
        sprintf(agBoxShm->device[nrow].device_code,"%s",qry.value(0).toString().toUtf8().data());
        sprintf(agBoxShm->device[nrow].device_id,"%s",qry.value(1).toString().toUtf8().data());
        agBoxShm->device[nrow].device_type = qry.value(2).toInt();
        sprintf(agBoxShm->device[nrow].product_code,"%s",qry.value(3).toString().toUtf8().data());
        sprintf(agBoxShm->device[nrow].device_gateway,"%s",qry.value(4).toString().toUtf8().data());
        nrow++;
    }
    for(int i=nrow;i<1024;i++){
        agBoxShm->device[i].Enabled = 0x00;
    }
    nrow = 0;
    qry.clear();
    sql.clear();
    sql = QString("select device_type,product_code,attribute_name,attribute_code from yt_t_attribute");
    qry = db.exec(sql);
    while (qry.next()) {
        if(nrow > 299)
            break;
        agBoxShm->procuctattrbute[nrow].Enabled = 0x01;
        agBoxShm->procuctattrbute[nrow].device_type = qry.value(0).toInt();
        sprintf(agBoxShm->procuctattrbute[nrow].product_code,"%s",qry.value(1).toString().toUtf8().data());
        sprintf(agBoxShm->procuctattrbute[nrow].attribute_name,"%s",qry.value(2).toString().toUtf8().data());
        sprintf(agBoxShm->procuctattrbute[nrow].attribute_code,"%s",qry.value(3).toString().toUtf8().data());
        nrow++;
    }
    for(int i=nrow;i<300;i++){
        agBoxShm->procuctattrbute[i].Enabled = 0x00;
    }

}

bool shm_load(){
    int shmid;
    key_t key;
    if((key=ftok(SHM_PATH,static_cast<int>(SHM_PORT)))==-1){
        return false;
    }
    if((shmid=shmget(key,sizeof (AGBoxShm),IPC_CREAT|0666))==-1){
        return false;
    }
    agBoxShm = static_cast<AGBoxShm *>(shmat(shmid,nullptr,0));

    shm_init();
    return true;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QDir path("/opt/agBoxProcess");
    if(!path.exists()){
        system("mkdir -p /opt/agBoxProcess");
        system("mkdir -p /opt/agBoxProcess/log");
    }
    db = QSqlDatabase::addDatabase("QSQLITE","conf_db");
    db.setDatabaseName(QString("/opt/db/yt_conf.db"));
    if(!db.open()){
        exit(1);
    }
    if(shm_load()){
        DogCore *dogcore = new DogCore(nullptr);
        dogcore->start();
    }else{
        fprintf(stderr,"shm load failed!\n");
        exit(1);
    }


    return a.exec();
}
