#MUDPyE - (M)ulti-(U)ser (D)imension (Py)thon (E)ngine
#Copyright (C) 2005  Corey Staten

#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.

#Send feedback/questions to MUDPyE@gmail.com

import os
import re

def ReadPropertiesFile(mudWorld, fileName):
  propertyDict = {}
  fileName = os.path.normpath(fileName)
  openFile = file(fileName, 'r')
  while 1:
    line = openFile.readline()
    if line == "":
      break
    elif line.strip() == "":
      continue
    result = re.match(r"(.*?)=(.*)", line.strip())
    if result == None:
      mudWorld.loggers["engine.fileloader"].warning("Invalid line in file %s." % (fileName))
      continue
    propertyDict[result.group(1)] = result.group(2)
  openFile.close()
  return propertyDict

def ReadTransitionFile(mudWorld, fileName):
  transitionDict = {}
  fileName = os.path.normpath(fileName)
  openFile = file(fileName, 'r')
  while 1:
    line = openFile.readline()
    if line == "":
      break
    elif line.strip() == "":
      continue
    result = re.match(r"from (.*?) to (.*)", line)
    if result == None:
      mudWorld.loggers["engine.fileloader"].warning("Invalid line in file [%s]." % (fileName))
      continue
    transitionDict[result.group(1)] = result.group(2)
  openFile.close()
  return transitionDict

def ReadIndexFile(mudWorld, fileName):
  indexList = []
  objectDict = {}
  fileName = os.path.normpath(fileName)
  try:
    openFile = file(fileName, 'r')
  except IOError:
    mudWorld.loggers["engine.fileloader"].error("Non-existant index file [%s]." % fileName)
    return {}
  dirName = os.path.dirname(fileName)
  while 1:
    line = openFile.readline()
    if line == "":
      break
    elif line.strip() == "":
      continue
    result1 = re.match(r"index (.*)", line)
    result2 = re.match(r"object (.*?) (.*)", line)
    if result1 != None:
      indexList.append(os.path.join(dirName, result1.group(1)))
    elif result2 != None:
      objectDict[result2.group(1)] = os.path.join(dirName, result2.group(2))
    else:
      mudWorld.loggers["engine.fileloader"].warning("Invalid line in file %s." % (fileName))
      continue
  openFile.close()
  for indexName in indexList:
    objectDict.update(ReadIndexFile(mudWorld, indexName))
  return objectDict