/**
 * @file motion.cc
 *
 * @brief this is the main file impelents motion
 *
 * @ingroup evcamera
 *
 * @author Bruce Lu
 * Contact: lzbgt@icloud.com
 *
 */

extern "C" {
#include <maque_type.h>
#include <maque_osd.h>
#include <maque_motion_detect.h>
#include <maque_debug.h>
}

#include <stdio.h>
#include <spdlog/spdlog.h>
#include <evpacket.h>
#include "motion.h"

typedef struct {
    MaQueMdParam_s stMdParam;
} MdModParam_s;

typedef struct {
    MaQueBdParam_s stBdParam;;
} BdModParam_s;

typedef struct {
    XM_S32 bMdEnabled;
    XM_S32 bBdEnabled;;
} MdBdMgr_s;

std::atomic<uint64_t> gMotionCounter(0);
extern shared_ptr<spdlog::logger> rlogger;

static XM_S32 cb_motion_detect(XM_VOID *pUserArg, MaQueMdAlarm_s *pstMdAlarm)
{
    //ev_module_config_t * pArgs = (ev_module_config_t *)pUserArg;
    gMotionCounter++;
    //rlogger->info("MD eAlarmType: {}, alarmState: {}", pstMdAlarm->eAlarmType, pstMdAlarm->alarmState);
    return 0;
}

static XM_S32 cb_blind_detect(XM_VOID *pUserArg, MaQueBdResult_s *pstBdRes)
{
    // ev_module_config_t * pArgs = (ev_module_config_t *)pUserArg;
    static int prevState = 0;

    if(pstBdRes->state != prevState) {
        if(pstBdRes->state == 1) {
            rlogger->info("The Camera is blind");
        }
        else {
            rlogger->info("The Camera is blind recovered");
        }
    }
    prevState = pstBdRes->state;
    return 0;
}

void start_md_bd(ev_module_config_t *pArgs)
{
    if(!pArgs->module.motion.enabled) {
        rlogger->warn("motion detect is disabled");
    }

    rlogger->info("starting motion detect module");
    MdModParam_s mdParam = { 0 };
    BdModParam_s bdParam = { 0 };

    // TODO: params setting from args
    mdParam.stMdParam.bEnabled = 1;
    mdParam.stMdParam.x = pArgs->module.motion.region.minx * 352;
    mdParam.stMdParam.y = pArgs->module.motion.region.miny * 288;
    mdParam.stMdParam.w = (pArgs->module.motion.region.maxx - pArgs->module.motion.region.minx) * 352;
    mdParam.stMdParam.h = (pArgs->module.motion.region.maxy - pArgs->module.motion.region.miny) * 288;
    mdParam.stMdParam.eMdAlarmlevel = (MaQueMdAlarmLevel_e)pArgs->module.motion.level; // [1, 6]

    /// Blind detection
    bdParam.stBdParam.bEnabled = 0;
    bdParam.stBdParam.eBdAlarmLevel = (MaQueBdAlarmLevel_e)pArgs->module.motion.level;

    if (mdParam.stMdParam.bEnabled) {
        LibXmMaQue_MD_create(0);
        LibXmMaQue_MD_setParam(0, &mdParam.stMdParam);
        LibXmMaQue_MDAlarm_register(0, cb_motion_detect, pArgs);
    }

    // if (bdParam.stBdParam.bEnabled) {
    //     LibXmMaQue_BD_create(0);
    //     LibXmMaQue_BD_setParam(0, &bdParam.stBdParam);
    //     LibXmMaQue_BD_register(0, cb_blind_detect, pArgs);
    // }
}

void stop_md_bd()
{
    LibXmMaQue_MD_destroy(0);
    LibXmMaQue_BD_destroy(0);
}


