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

def __centerView(self, envelope):
    self.getMapContext().getViewPort().setEnvelope(envelope)

def __showWindow(self, maximize=False):
    application = ApplicationLocator.getManager() # Manager app
    projectManager = application.getProjectManager() # Project manager

    viewManager = projectManager.getDocumentManager(ViewManager.TYPENAME)
    view = currentProject().getView(self.name)
    viewin = viewManager.getMainWindow(view, None) #got our view
    application.getUIManager().addWindow(viewin) #open into the project
    if maximize:
        application.getUIManager().setMaximum(viewin, True) #all window size

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 __getWindowOfView(self):
    application = ApplicationLocator.getManager()
    projectManager = application.getProjectManager()
    viewManager = projectManager.getDocumentManager(ViewManager.TYPENAME)
    return viewManager.getMainWindow(self,None)

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


#
# Inject new methods in the class JViewDocument
#
JViewDocument.centerView = __centerView
JViewDocument.showWindow = __showWindow
JViewDocument.getLayer = __getLayer
JViewDocument.getLayers = __getLayers
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
JViewDocument.getWindowOfView = __getWindowOfView



