#include "stdafx.h"
#include "monkeycar_area.h"
#include "classdef.h"

monkey_area::monkey_area(std::shared_ptr<db_area> db_area_ptr)
	:area(db_area_ptr)
	,m_path(db_area_ptr->m_point.begin(),db_area_ptr->m_point.end())
{
		//反向
	std::shared_ptr<monkey_bus> bus = std::make_shared<monkey_bus>(db_area_ptr->m_default_speed,NEGTIVE_DIRECTION);
	bus_.push_back(bus);
	//正向
	//这里需要吧vector里面的字段逆序，然后放入到fp_path里
	bus = std::make_shared<monkey_bus>(db_area_ptr->m_default_speed * -1.0,POSTIVE_DIRECTION);
	bus_.push_back(bus);
	for (auto bus:bus_)
	{
		bus->start();
	}
}


std::shared_ptr<monkey_person> monkey_area::find(std::string cardid)
{
	ScopedLock lk(m_monitor);
	auto it =  card_map_.find(cardid);
	if(it == card_map_.end())
		return nullptr;
	return it->second;
}

void monkey_area::on_card_leave(const std::string& cardid, int next_area)
{
	debug_print_syslog(0,"[framework on_card_leave]cardId:%s,pre_areaId:%d",cardid.c_str(),next_area);
	ScopedLock lk(m_monitor);
	auto it = card_map_.find(cardid);
	if (it != card_map_.end())
	{
		if (it->second->is_on_bus())
		{
			if (!it->second->m_bus.expired())
			{
				std::shared_ptr<monkey_bus> tbus = it->second->m_bus.lock();
				//
				tbus->getOffTheBus(it->second);
			}
			
		}
		card_map_.erase(it);
	}
	
}
void monkey_area::on_card_enter(std::shared_ptr<Card>& ccard, int prev_area)
{
	debug_print_syslog(0,"[framework on_card_enter]cardId:%s,pre_areaId:%d",ccard->card_id.c_str(),prev_area);
	std::shared_ptr<monkey_person> mp = std::make_shared<monkey_person>(ccard,this);
	mp->m_person->set_position_interface(mp);
	ScopedLock lk(m_monitor);
	card_map_.insert(std::make_pair(ccard->card_id,mp));
}
void monkey_area::on_card_move(std::shared_ptr<Card> &card)
{
	//debug_print_syslog(0,"[framework on_card_move]cardId:%s",card->card_id.c_str());
	auto mp=find(card->card_id);
	if (!mp)
	{
		//if not exist create it .because may be restart the system.then area not changed.
		on_card_enter(card,card->pre_area_id); 
		return ;
	}
	bool ret = mp->on_step_map(m_path);
	if (!ret)
	{
		return;
	}
	double speed=0;
	bool b=mp->fit_speed(&speed);
	if (!b || speed == DBL_MAX)
	{
		return ;
	}
	//on bus
	speed *= cacti::Timestamp::ONE_SEC_IN_MILLISEC;
	if(mp->is_on_bus())
	{
		if (!mp->m_bus.expired())
		{
			std::shared_ptr<monkey_bus> tbus = mp->m_bus.lock();
			if(!tbus->test_get_off(mp,speed))
			{
				tbus->getOffTheBus(mp);	
			}
		}
		
	}
	else
	{
		std::shared_ptr<monkey_bus> bus=bus_[speed>0?0:1];
		if(bus->test_get_on(mp,speed))
		{
			bus->getOnTheBus(mp,bus);	
			
		}
	}
}
