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

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

    //well, let's cue it then

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

}

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

    SendMsgEx(msg, deliveryTime);

}

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

}

void MessageDispatcher::KillMessageType(int msg)
{
    
    for ( std::list<Message>::iterator it = m_message.begin(); it != m_message.end(); ++it)
    {
        {
            if ( (*it).msg == msg)
            {
                (*it).bDeleteMe = 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).bDeleteMe) )   
        {
            //time to delivery this bitch!
            DeliverMsg(*it);
        }
    }

    //remove any old messages

  
    for (it = m_message.begin();it != m_message.end(); ++it)
    {
        if ((*it).m_deliveryTime < CL_System::get_time())   
        {
            //time to delivery this bitch!
            if ((*it).bDeleteMe)
            {
                it = m_message.erase(it);
            }
        }
    }


}


void MessageDispatcher::SendMsg(int message, int deliveryTimeMS, Entity *pEnt /* = NULL */, int parm1)
{
    Message msg;
    msg.msg = message;
    msg.pDeliveryTarget = pEnt;
    msg.parm1 = parm1;
    SendMsgEx(msg, deliveryTimeMS);
}

void MessageDispatcher::ClearAllMessages()
{
    //much safer than a .clear(), because we might be in the Update() right now
    
    for ( std::list<Message>::iterator it = m_message.begin(); it != m_message.end(); ++it)
    {
        {
                  (*it).bDeleteMe = true;
        }
    }

}

void MessageDispatcher::DeliverMsg(Message &msg)
{
    if (msg.pDeliveryTarget)
    {
        msg.pDeliveryTarget->OnMessage(msg);
    }   else
    {
        GetGameLogic->OnMessage(msg);
        //send to everybody
         GetMyEntityMgr->OnMessage(msg);
    }

    msg.bDeleteMe = true;

}

