#include "lightingcore.h"
#include "../AGBoxDog/boxshm.h"
#include "../agVideoProcess/boxdeviceshm.h"
AGBoxShm *agBoxShm;
BoxDeviceShm *boxDeviceShm;

void LightingCore::shm_init(){
    QSqlQuery qry;
    QString sql = QString("select mqtt_ip,mqtt_port,user_name,pass_word from yt_t_mqtt where item_name = 'data-agbox'");
    qry = db.exec(sql);
    while (qry.next()) {
        ip = qry.value(0).toString();
        port = qry.value(1).toString();
        username = qry.value(2).toString();
        password = qry.value(3).toString();
    }
    qry.clear();
    sql.clear();

}

bool LightingCore::shm_load(){
    key_t key;
    int shmid;
    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));

    if((key=ftok(VIDEO_PATH,static_cast<int>(VIDEO_PORT)))==-1){
        return false;
    }
    if((shmid=shmget(key,sizeof(BoxDeviceShm),IPC_CREAT|0666))==-1){
        return false;
    }
    boxDeviceShm = static_cast<BoxDeviceShm *>(shmat(shmid,nullptr,0));

    shm_init();
    return true;
}

LightingCore::LightingCore(QObject *parent) : QObject(parent)
{
    logthread = new LogThread(this);
    logthread->start();

    db = QSqlDatabase::addDatabase("QSQLITE","conf_db");
    db.setDatabaseName(QString("/opt/db/yt_conf.db"));
    if(!db.open()){
        logthread->appendData(QString("[agenvironment] open yt_conf.db failed"));
    }
    if(shm_load()){
        logthread->appendData(QString("[agenvironment] shm load success"));
    }

    mqttIdx = 1;
    m_client = new QMQTT::Client(QHostAddress(ip),static_cast<quint16>(port.toInt()),this);
    connect(m_client,&QMQTT::Client::connected,this,&LightingCore::onConnected);
    m_client->setUsername(username);
    m_client->setPassword(password.toLatin1());
    m_client->setCleanSession(true);
    m_client->connectToHost();

    clientthread = new ClientThread(this);
    connect(clientthread,&ClientThread::mqttData,this,&LightingCore::mqtt_data);
    connect(clientthread,&ClientThread::dataListLog,this,&LightingCore::dataLog);
    connect(clientthread,&ClientThread::responseMsg,this,&LightingCore::response_msg);

    tcpserver = new TcpServer(this);
    connect(tcpserver,&TcpServer::control_data,this,&LightingCore::control_data);
    connect(tcpserver,&TcpServer::tcp_log,this,&LightingCore::dataLog);

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&LightingCore::time_out);
    timer->start(60000);

}


LightingCore::~LightingCore()
{
    logthread->stop();
    clientthread->stop();
}

void LightingCore::start()
{
    clientthread->start();
    tcpserver->start();

    time_out();
}

void LightingCore::control_data(QString deviceId,int switchStatus)
{
    clientthread->controlData(deviceId,switchStatus);
}

void LightingCore::time_out()
{

    agBoxShm->processStatus[6].t_time = QDateTime::currentDateTime().toTime_t();

    clientthread->deviceStatus();
    for(int i=0;i<1024;i++){
        if((boxDeviceShm->device[i].Enabled == 0x01)&&(boxDeviceShm->device[i].device_type == 510)){
            uint curTime = QDateTime::currentDateTime().toTime_t();
            if((curTime - boxDeviceShm->device[i].lastTime)>120){
                boxDeviceShm->device[i].lastTime = curTime;
                this->mqtt_data(QString("{\"device_id\":\"%1\",\"device_code\":\"%2\",\"product_id\":\"%3\",\"timestamp\":%4,\"tags\":{\"conn_type\":\"\",\"type\":\"\"},\"metrics\":{\"device_status\":0},\"device_type\":\"%5-lg\"}")
                              .arg(boxDeviceShm->device[i].device_id).arg(boxDeviceShm->device[i].device_code).arg(boxDeviceShm->device[i].company_code).arg(curTime).arg(boxDeviceShm->device[i].device_type));
            }
        }
    }
}

void LightingCore::response_msg(QString msg)
{
    tcpserver->response_msg(msg);
}

void LightingCore::onConnected()
{
    logthread->appendData(QString("mqtt onConnected"));
}

void LightingCore::dataLog(QString log)
{
    logthread->appendData(log);
}

void LightingCore::mqtt_data(QString mqtt_msg)
{
    printf("test6666 [%s]\n",mqtt_msg.toUtf8().data());
    if((m_client->connectionState()==QMQTT::STATE_INIT)||(m_client->connectionState()==QMQTT::STATE_DISCONNECTED)){
        m_client->connectToHost();
    }
    m_client->publish(QMQTT::Message(mqttIdx++,"data-collector",mqtt_msg.toUtf8()));
    if(mqttIdx > 9999){
        mqttIdx = 1;
    }
}
