#include "MessageDispatcher.h"
#include "GameLogic.h"
#include "Entity.h"

void MessageDispatcher::SendMsgEx(Message &msg, int deliveryTimeMS)
{
    if (deliveryTimeMS == 0)
    {
        DeliverMsg(msg);
        return;
    }

    msg.m_deliveryTime = CL_System::get_time() + deliveryTimeMS;
    m_message.push_back(msg);
}

void MessageDispatcher::SendText(std::string text, int deliveryTime, int delayTime)
{
    Message msg;
    msg.m_msg = C_MESSAGE_TEXT;
    msg.m_text = text;
	msg.m_parm = delayTime;

    SendMsgEx(msg , deliveryTime);
}

void MessageDispatcher::KillAllMessagesToThisEnt(Entity *pEnt)
{
    for ( std::list<Message>::iterator it = m_message.begin(); it != m_message.end(); ++it)
    {
         {
            if ( (*it).m_pDeliveryTarget == pEnt)
            {
                (*it).m_bDeleteRequest = true;
            }
        }
    }

}

void MessageDispatcher::KillMessageType(int msg)
{
    
    for ( std::list<Message>::iterator it = m_message.begin(); it != m_message.end(); ++it)
    {
        {
            if ( (*it).m_msg == msg)
            {
                (*it).m_bDeleteRequest = true;
            }
        }
    }
    
}

void MessageDispatcher::Update()
{
    std::list<Message>::iterator it;
    
    for (it= m_message.begin(); it != m_message.end(); ++it)
    {
        if ((*it).m_deliveryTime < CL_System::get_time() && (!(*it).m_bDeleteRequest) )   
        {
            DeliverMsg(*it);
        }
    }

    for (it = m_message.begin();it != m_message.end();)
    {
        if ((*it).m_deliveryTime < CL_System::get_time())   
        {
            if ((*it).m_bDeleteRequest)
            {
                it = m_message.erase(it);
				continue;
            }
        }
		it++;
    }
}


void MessageDispatcher::SendMsg(int message, int deliveryTimeMS, Entity *pEnt /* = NULL */, int parm)
{
    Message msg;
    msg.m_msg = message;
    msg.m_pDeliveryTarget = pEnt;
    msg.m_parm = parm;
    SendMsgEx(msg, deliveryTimeMS);

}

void MessageDispatcher::ClearAllMessages()
{
      
    for ( std::list<Message>::iterator it = m_message.begin(); it != m_message.end(); ++it)
    {
        {
                  (*it).m_bDeleteRequest = true;
        }
    }

}

void MessageDispatcher::DeliverMsg(Message &msg)
{
    if (msg.m_pDeliveryTarget)
    {
        msg.m_pDeliveryTarget->OnMessage(msg);

	}   else
    {

		GetGameLogic->OnMessage(msg);
         GetMyEntityMgr->OnMessage(msg);
    }

    msg.m_bDeleteRequest = true;
}

