#include "gsd_ExpelPlugin.h"
#include "expel.h"

using namespace drogon;
using namespace gsd;

void ExpelPlugin::initAndStart(const Json::Value &config)
{
    /// Initialize and start the plugin
    DebugL;
    this->sockerUdp = Socket::createSocket();
    if(this->Init() != OK){
        ErrorL << "ExpelPlugin初始化失败" << endl;
    }
}

void ExpelPlugin::shutdown() 
{
    /// Shutdown the plugin
}

/**
* @description: 初始化
* @return {*}
*/    
int8_t ExpelPlugin::Init(){
    this->sockerUdp->bindUdpSock(7777);
    this->sockerUdp->setOnRead([&](const Buffer::Ptr &buf, struct sockaddr *addr , int){
       this->UdpRecData(buf);
    });
    return OK;
}

/**
 * @description: 启动任务
 * @return {*}
 */
void ExpelPlugin::StartTask(){


}

/**
 * @description: 
 * @param {sockaddr} *out
 * @param {char} *ip
 * @param {uint16_t} port
 * @return {*}
 */
void ExpelPlugin::makeAddr(struct sockaddr *out,const char *ip,uint16_t port){
    struct sockaddr_in &servaddr = *((struct sockaddr_in *)out);
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = inet_addr(ip);
    bzero(&(servaddr.sin_zero), sizeof servaddr.sin_zero);
}

/**
 * @description: UDP数据接收
 * @param {Ptr} &buf
 * @return {*}
 */
void ExpelPlugin::UdpRecData(const Buffer::Ptr &buf){
    static std::shared_ptr<Ticker> ticker = nullptr;
    string json = buf->toString();
    std::shared_ptr<CNStreamInferData> cnstreamInferData = nullptr;
    cnstreamInferData = std::make_shared<CNStreamInferData>();
    DebugL << json << endl;
    if(cnstreamInferData->jsonToObject(json)){
        vector<vector<std::string>> result;
        SqlWriter sqlSelete("SELECT DeviceId,DeviceToken,DeviceType, \
            ServerIp,ServerCname,ServerCpwd FROM gsdDB.`DeviceList` WHERE ISDELETE = 0");
        sqlSelete << result;

        Expel::getPtr()->UpdateDeviceList(result);
  
        InfineFilter::getPtr()->bboxSize = config::getPtr()->bboxSize;
        // 过滤小目标
        InfineFilter::getPtr()->MinBBoxFilter(cnstreamInferData);
        
        if(cnstreamInferData->Objects.size()){
            if(ticker != nullptr) ticker->resetTime();
            if(this -> m_DevPowerState == false){
                // 控制驱鸟设备
                Expel::getPtr() -> AllFire();
                // 更新状态
                this -> m_DevPowerState = true;
            }
        }else{
            if(ticker == nullptr) ticker = std::make_shared<Ticker>();
            int time = config::getPtr()->ExpelInterval;
            if(ticker->elapsedTime() > time && this->m_DevPowerState){
                this->m_DevPowerState = false;
                ticker = nullptr;
                Expel::getPtr() -> AllClose();
            }
        }
    }
}



