#include"module_motionless_persion.h"


#include"common_tool.h"
#include"log.h"
#include"area.h"
#include"event.h"
#include"tool_time.h"
#include"area_business.h"


struct motionless_data:business_data
{
    motionless_data()
    {
        m_acc_0count=0;
        m_acc_start_time=0;
    }

    ///;检测到多少次之后定位完全静止
    std::atomic<int> m_acc_0count;
    ///检测到多久之后告警
    time_t m_acc_start_time;
};

void module_motionless_persion::on_enter(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }

    area_hover_ptr->m_data[index] = std::make_shared<motionless_data>();
}

void module_motionless_persion::on_hover(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }
    auto ptr = static_cast<motionless_data*>(area_hover_ptr->m_data[index].get());
    if(0 == static_cast<int>(card_ptr->m_acc))
    {
        ptr->m_acc_0count++;
    }
    else
    {
        ptr->m_acc_0count=0;
    }
}

void module_motionless_persion::on_leave(std::shared_ptr<card_location_base> card_ptr, int index)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }

    uint64_t id = tool_other::type_id_to_u64(card_ptr->m_type, card_ptr->m_id);
    event_tool::instance()->handle_event(OT_CARD, ET_CARD_MOTIONLESS, id, 0, 0, false);

    area_hover_ptr->m_data[index] = std::make_shared<motionless_data>();
}

void module_motionless_persion::deal_alarm(std::shared_ptr<card_location_base>& card_ptr)
{
    auto area_hover_ptr = card_ptr->get_area_hover();
    if(!area_hover_ptr)
    {
        log_error("if(!area_hover_ptr)==true");
        return;
    }

    auto arr = area_hover_ptr->m_data;
    int index = 1;

    if(arr.size()<2 || !arr[index])
    {
        return;
    }

    auto ptr = static_cast<motionless_data*>(area_hover_ptr->m_data[index].get());

    if(ptr->m_acc_0count >= _acc_0count_limit)
    {
        ptr->m_acc_0count = _acc_0count_limit;
        if(0 == ptr->m_acc_start_time)
        {
            ptr->m_acc_start_time = tool_time::now_to_seconds();
        }
    }
    else
    {
        ptr->m_acc_start_time=0;
    }

    bool is_alarm = (0 != ptr->m_acc_start_time
            &&tool_time::elapse_seconds(ptr->m_acc_start_time)> _acc_seconds_limit);

    uint64_t id = tool_other::type_id_to_u64(card_ptr->m_type, card_ptr->m_id);
    event_tool::instance()->handle_event(OT_CARD, ET_CARD_MOTIONLESS, id, 0, 0, is_alarm);
}




