

from org.gvsig.app.project import DefaultProject as JProject
from org.gvsig.app import ApplicationLocator
from org.gvsig.app.project.documents.view import ViewDocument
from org.gvsig.app.project.documents.table import TableDocument

def __getView(self, name=None):
  if name == None:
    try:
      activeDocument = self.getActiveDocument()
      if activeDocument == None:
	  return None
      if isinstance(activeDocument, ViewDocument):
	  return activeDocument
      return None
    
    except Exception, ex:
      raise Exception("%s" % repr(ex))
  else:
    views = self.getViews()
    if len(views) >0:
      for view in views:
	if name == view.getName():
	  return view
    return None
    
def __getTable(self, name=None):
  if name == None:
    try:
      activeDocument = self.getActiveDocument()
      if activeDocument == None:
	  return None
      if isinstance(activeDocument, TableDocument):
	  return activeDocument
      return None
    
    except Exception, ex:
      raise Exception("%s"%repr(ex))
  else:
    tables = self.getDocuments("project.document.table")
    if len(tables) >0:
      for table in tables:
	if name == table.getName():
	  return table
    return None   

def __getProjectionCode(self):
  return self.getProjection().getFullCode()

def __call(self):
  return self

def __iter(self):
  it = self.iterator()
  while it.hasNext() :
    doc = it.next()
    yield doc

def __len(self):
  return self.getDocuments().size()

def __getitem(self,index):
  return self.getDocuments().get(index)
  
def currentProject():
  application = ApplicationLocator.getManager()
  project = application.getCurrentProject()
  return project

def currentDocument(documentClass = None):
  application = ApplicationLocator.getManager()
  
  if documentClass == None:
    doc = application.getActiveDocument()
  else:
    doc = application.getActiveDocument(documentClass)
  return doc
  
def currentTable():
  return currentDocument(TableDocument)
  
def currentView():
  return currentDocument(ViewDocument)



    
#
# Inject new methods in the class JProject
#
JProject.getView = __getView
JProject.getTable = __getTable
JProject.getProjectionCode = __getProjectionCode
JProject.__call__ = __call
JProject.__iter__ = __iter
JProject.__len__ = __len
JProject.__getitem__ = __getitem

