/*
 * Copyright (C) 2005-2008 MaNGOS 
 *
 * Copyright (C) 2008 Trinity 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Policies/SingletonImp.h"
#include "Player.h"
#include "Creature.h"
#include "GameObject.h"
#include "DynamicObject.h"
#include "Corpse.h"
#include "WorldSession.h"
#include "WorldPacket.h"
#include "Item.h"
#include "Corpse.h"
#include "GridNotifiers.h"
#include "MapManager.h"
#include "Map.h"
#include "CellImpl.h"
#include "GridNotifiersImpl.h"
#include "Opcodes.h"
#include "ObjectDefines.h"
#include "MapInstanced.h"
#include 
#define CLASS_LOCK Trinity::ClassLevelLockable
INSTANTIATE_SINGLETON_2(ObjectAccessor, CLASS_LOCK);
INSTANTIATE_CLASS_MUTEX(ObjectAccessor, ZThread::FastMutex);
namespace Trinity
{
    struct TRINITY_DLL_DECL BuildUpdateForPlayer
    {
        Player &i_player;
        UpdateDataMapType &i_updatePlayers;
        BuildUpdateForPlayer(Player &player, UpdateDataMapType &data_map) : i_player(player), i_updatePlayers(data_map) {}
        void Visit(PlayerMapType &m)
        {
            for(PlayerMapType::iterator iter=m.begin(); iter != m.end(); ++iter)
            {
                if( iter->getSource() == &i_player )
                    continue;
                UpdateDataMapType::iterator iter2 = i_updatePlayers.find(iter->getSource());
                if( iter2 == i_updatePlayers.end() )
                {
                    std::pair p = i_updatePlayers.insert( ObjectAccessor::UpdateDataValueType(iter->getSource(), UpdateData()) );
                    assert(p.second);
                    iter2 = p.first;
                }
                i_player.BuildValuesUpdateBlockForPlayer(&iter2->second, iter2->first);
            }
        }
        template void Visit(GridRefManager &) {}
    };
}
ObjectAccessor::ObjectAccessor() {}
ObjectAccessor::~ObjectAccessor() {}
Creature*
ObjectAccessor::GetNPCIfCanInteractWith(Player const &player, uint64 guid, uint32 npcflagmask)
{
    // unit checks
    if (!guid)
        return NULL;
    // exist
    Creature *unit = GetCreature(player, guid);
    if (!unit)
        return NULL;
    // player check
    if(!player.CanInteractWithNPCs(!unit->isSpiritService()))
        return NULL;
    // appropriate npc type
    if(npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
        return NULL;
    // alive or spirit healer
    if(!unit->isAlive() && (!unit->isSpiritService() || player.isAlive() ))
        return NULL;
    // not allow interaction under control
    if(unit->GetCharmerOrOwnerGUID())
        return NULL;
    // not enemy
    if( unit->IsHostileTo(&player))
        return NULL;
    // not unfriendly
    FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction());
    if(factionTemplate)
    {
        FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction);
        if( faction->reputationListID >= 0 && player.GetReputationRank(faction) <= REP_UNFRIENDLY)
            return NULL;
    }
    // not too far
    if(!unit->IsWithinDistInMap(&player,INTERACTION_DISTANCE))
        return NULL;
    return unit;
}
Creature*
ObjectAccessor::GetCreatureOrPet(WorldObject const &u, uint64 guid)
{
    if(Creature *unit = GetPet(guid))
        return unit;
    return GetCreature(u, guid);
}
Creature*
ObjectAccessor::GetCreature(WorldObject const &u, uint64 guid)
{
    Creature * ret = GetObjectInWorld(guid, (Creature*)NULL);
    if(!ret)
        return NULL;
    if(ret->GetMapId() != u.GetMapId())
        return NULL;
    if(ret->GetInstanceId() != u.GetInstanceId())
        return NULL;
    return ret;
}
Unit*
ObjectAccessor::GetUnit(WorldObject const &u, uint64 guid)
{
    if(!guid)
        return NULL;
    if(IS_PLAYER_GUID(guid))
        return FindPlayer(guid);
    return GetCreatureOrPet(u, guid);
}
Corpse*
ObjectAccessor::GetCorpse(WorldObject const &u, uint64 guid)
{
    Corpse * ret = GetObjectInWorld(guid, (Corpse*)NULL);
    if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
    return ret;
}
Object* ObjectAccessor::GetObjectByTypeMask(Player const &p, uint64 guid, uint32 typemask)
{
    Object *obj = NULL;
    if(typemask & TYPEMASK_PLAYER)
    {
        obj = FindPlayer(guid);
        if(obj) return obj;
    }
    if(typemask & TYPEMASK_UNIT)
    {
        obj = GetCreatureOrPet(p,guid);
        if(obj) return obj;
    }
    if(typemask & TYPEMASK_GAMEOBJECT)
    {
        obj = GetGameObject(p,guid);
        if(obj) return obj;
    }
    if(typemask & TYPEMASK_DYNAMICOBJECT)
    {
        obj = GetDynamicObject(p,guid);
        if(obj) return obj;
    }
    if(typemask & TYPEMASK_ITEM)
    {
        obj = p.GetItemByGuid( guid );
        if(obj) return obj;
    }
    return NULL;
}
GameObject*
ObjectAccessor::GetGameObject(WorldObject const &u, uint64 guid)
{
    GameObject * ret = GetObjectInWorld(guid, (GameObject*)NULL);
    if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
    return ret;
}
DynamicObject*
ObjectAccessor::GetDynamicObject(Unit const &u, uint64 guid)
{
    DynamicObject * ret = GetObjectInWorld(guid, (DynamicObject*)NULL);
    if(ret && ret->GetMapId() != u.GetMapId()) ret = NULL;
    return ret;
}
Player*
ObjectAccessor::FindPlayer(uint64 guid)
{
    return GetObjectInWorld(guid, (Player*)NULL);
}
Player*
ObjectAccessor::FindPlayerByName(const char *name)
{
    //TODO: Player Guard
    HashMapHolder::MapType& m = HashMapHolder::GetContainer();
    HashMapHolder::MapType::iterator iter = m.begin();
    for(; iter != m.end(); ++iter)
        if( ::strcmp(name, iter->second->GetName()) == 0 )
            return iter->second;
    return NULL;
}
void
ObjectAccessor::SaveAllPlayers()
{
    Guard guard(*HashMapHolder::GetLock());
    HashMapHolder::MapType& m = HashMapHolder::GetContainer();
    HashMapHolder::MapType::iterator itr = m.begin();
    for(; itr != m.end(); ++itr)
        itr->second->SaveToDB();
}
void
ObjectAccessor::UpdateObject(Object* obj, Player* exceptPlayer)
{
    UpdateDataMapType update_players;
    obj->BuildUpdate(update_players);
    WorldPacket packet;
    for(UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter)
    {
        if(iter->first == exceptPlayer)
            continue;
        iter->second.BuildPacket(&packet);
        iter->first->GetSession()->SendPacket(&packet);
        packet.clear();
    }
}
void
ObjectAccessor::AddUpdateObject(Object *obj)
{
    Guard guard(i_updateGuard);
    i_objects.insert(obj);
}
void
ObjectAccessor::RemoveUpdateObject(Object *obj)
{
    Guard guard(i_updateGuard);
    std::set