/*

 BabbleMud - A MUD server

 Author:  Nick Gammon 
          http://www.gammon.com.au/ 

(C) Copyright Nick Gammon 2004. Permission to copy, use, modify, sell and
distribute this software is granted provided this copyright notice appears
in all copies. This software is provided "as is" without express or implied
warranty, and with no claim as to its suitability for any purpose.
 
*/

// standard library includes ...

#include <stdexcept>

using namespace std; 

#include "utils.h"
#include "room.h"
#include "globals.h"

World & FindRoom (const int & vnum)
{
  WorldMapIterator i = world ().find (vnum);
  
  if (i == world ().end ())
    throw msg ("room_does_not_exist");

  return i->second;
}


// room short name
const string World::roomName         (const string & prefix) const
  {
  return roomString (prefix + "short", 
        MAKE_STRING ("<<Room " << roomNumber ("vnum") << ":" << prefix << "short>>"));
  } // end of World::roomName 

// room long description
const string World::roomDescription  (const string & prefix) const
  {
  return roomString (prefix + "description", 
        MAKE_STRING ("<<Room " << roomNumber ("vnum") << ":" << prefix << "description>>"));   
  } // end of World::roomDescription 

void RebuildRoom (ObjectList::const_iterator & roomIter)
  {
const Object & room = *roomIter;   // the room
int vnum = room.geti ("vnum");   // get the vnum

  if (vnum == 0)    // ignore if no vnum
    return;
  
  WorldMap::iterator worldIter = world ().find (vnum);

  // if room in world map, just remember iterator to corresponding room
  if (worldIter != world ().end ())
    {
    worldIter->second.room_ = roomIter;
    return;
    }
  
  // make a new one, add to map
  World w;
  w.room_ = roomIter;
  
  // insert into map
  world () [vnum] = w; 
  }

// we have to do this after changing the rooms list
void RebuildWorldMap ()
  {
  
  // no room yet for any world item  
  for (WorldMap::iterator wi = world ().begin ();
       wi != world ().end ();
       ++wi)
    wi->second.room_ = rooms ().end ();
  
  // add room iterators to world items
  for (ObjectList::const_iterator i = rooms ().begin ();
       i != rooms ().end ();
       ++i)
    RebuildRoom (i);  
  
  // delete rooms which did not have iterators
  for (WorldMap::iterator wi = world ().begin ();
     wi != world ().end ();
     )
    {
    // see Josuttis p 205
    if (wi->second.room_ == rooms ().end ())
      world ().erase (wi++);
    else
      ++wi;
    } // end of doing each world item
 
  } // end of RebuildWorldMap
