#ifndef MODULE_AREA_TIMEOUT_H
#define MODULE_AREA_TIMEOUT_H

/**
  *@brief 区域超时模块 2018-08-26 戴月腾修改
  * 当某张人卡在某个区域的时间超过指定值时，会发出区域超时告警
  * @author 陈欧美
  * @date 2018-08-05
*/

#include <mutex>
#include <map>
#include <chrono>
#include <boost/thread.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "point.h"
#include "module_const.h"
#include"module_const.h"


/**
 * @brief 当某张人卡在某个区域的时间超过指定值时，会发出区域超时告警
 */
class module_area_timeout:public singleton_base<module_area_timeout>
{
private:
    friend class singleton_base<module_area_timeout>;
    module_area_timeout()
    {
    }

public:
    void on_enter(std::shared_ptr<card_location_base> card_ptr,std::shared_ptr<area_hover>&c,double speed)
    {
        c->m_is_area_over_time_person=false;
    }

    void on_hover(std::shared_ptr<card_location_base> card_ptr,std::shared_ptr<area_hover>&c,double speed,
                  std::map<uint64_t, std::shared_ptr<ya_event>>& ev_map)
    {
        auto area_ptr = c->m_area;

        int seconds = tool_time::elapse_seconds(c->m_enter_time);

        if(seconds > area_ptr->m_limit_time_second)//发生告警
        {
            auto ev_ptr = tool_other::find_event(card_ptr->m_id, ET_CARD_AREA_OVER_TIME_PERSON, ev_map);
            if(ev_ptr)
            {
                ev_ptr->m_limit_value=area_ptr->m_limit_time_second;
                ev_ptr->m_cur_value=seconds;
            }
            else//从没有告警状态转化为告警状态
            {
                c->m_is_area_over_time_person=true;//发生告警
                auto ev_ptr = tool_other::create_event(OT_CARD, card_ptr->m_id, ET_CARD_AREA_OVER_TIME_PERSON);

                tool_other::copy_event(card_ptr, ev_ptr);

                ev_ptr->m_limit_value = area_ptr->m_limit_time_second;
                ev_ptr->m_cur_value = seconds;

                //保存到数据库
                tool_db::save_event(ev_ptr);

                tool_other::insert_event(ev_ptr, ev_map);
            }
        }
        else
        {
            if(c->m_is_area_over_time_person)
            {
                c->m_is_area_over_time_person = false;
                auto ev_ptr = tool_other::find_event(card_ptr->m_id, ET_CARD_AREA_OVER_TIME_PERSON, ev_map);
                if(ev_ptr)
                {
                    ev_ptr->m_status = ES_END;

                    ev_ptr->m_limit_value = area_ptr->m_limit_time_second;
                    ev_ptr->m_cur_value = seconds;
                    ev_ptr->m_cur_time = std::chrono::system_clock::now();

                    //保存到数据库
                    tool_db::save_event(ev_ptr);
                }
            }
        }
    }

    void on_leave(std::shared_ptr<card_location_base> card_ptr,std::shared_ptr<area_hover>&c,double speed)
    {

    }
};
typedef std::shared_ptr<module_area_timeout> module_area_timeout_ptr;

#endif // MODULE_AREA_TIMEOUT_H
