
from org.gvsig.app.project.documents.view import DefaultViewDocument as JViewDocument
from org.gvsig.fmap.mapcontext.layers import FLayers
from project import currentView

def __getLayer(self, name=None):
  layers = self.getMapContext().getLayers()
  if name != None:
    return layers.getLayer(name)
  
  activeLayers = layers.getActives()
  if len(activeLayers) != 1 :
    return None
  for layer in activeLayers:
    if not isinstance(layer, FLayers):
      return layer
  return None

def __getMap(self):
  return self.getMapContext();

def __addLayer(self, layer):
  self.getMapContext().getLayers().addLayer(layer)

def __getLayers(self):
  return self.getMapContext().getLayers()

def __iter(self):
  return self.getMapContext().getLayers().__iter__()

def __len(self):
  return self.getMapContext().getLayers().getLayersCount()

def __getitem(self, index):
  return self.getMapContext().getLayers().getLayer(index)

def __getGraphicsLayer(self):
  return self.getMapContext().getGraphicsLayer()

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

def __call(self):
  return self


def currentLayer():
  try:
    return currentView().getLayer()
  except:
    return None
  

#
# Inject new methods in the class JViewDocument
#
JViewDocument.getLayer = __getLayer
JViewDocument.getMap = __getMap
JViewDocument.addLayer = __addLayer
JViewDocument.getGraphicsLayer = __getGraphicsLayer
JViewDocument.getProjectionCode = __getProjectionCode
JViewDocument.isProjected = __isProjected
JViewDocument.__call__ = __call
JViewDocument.__iter__ = __iter
JViewDocument.__len__ = __len
JViewDocument.__getitem__ = __getitem



