# encoding: utf-8

import gvsig

from gvsig.uselib import use_plugin
use_plugin("org.gvsig.vcsgis.app.mainplugin")

from gvsig import getResource
from gvsig.commonsdialog import inputbox, msgbox,  QUESTION, WARNING, YES, YES_NO

from java.util import Collections
from java.lang import Throwable
from javax.swing import JPopupMenu
from javax.swing import JSeparator
from javax.swing import JMenuItem

from org.gvsig.andami import PluginsLocator
from org.gvsig.tools.swing.api import ToolsSwingLocator
from org.gvsig.fmap.dal.store.jdbc import JDBCServerExplorerParameters
from org.gvsig.fmap.mapcontext import MapContextLocator
from org.gvsig.fmap.dal.swing import DALSwingLocator
from org.gvsig.tools.swing.api import ToolsSwingLocator
from org.gvsig.tools import ToolsLocator
from org.gvsig.tools.dispose import DisposeUtils
from org.gvsig.tools.swing.api.windowmanager import WindowManager, WindowManager_v2

from addons.Catalog.catalogutils import CatalogNode, CatalogSimpleNode, createJMenuItem, getDataManager, getIconFromParams
from addons.Catalog.catalogutils import openAsTable, openAsForm, openSearchDialog, openAsParameters, addToBookmarks
from addons.Catalog.catalogutils import openAsLayer

from org.gvsig.fmap.dal.exception import ValidateDataParametersException

from org.gvsig.app import ApplicationLocator
from org.gvsig.app.project.documents.table import TableManager

from javax.swing import SwingUtilities
from java.io import File
from javax.imageio import ImageIO
from javax.swing import ImageIcon

from  addons.Catalog.cataloglocator import getCatalogManager

from org.gvsig.vcsgis.lib import VCSGisLocator
from org.gvsig.vcsgis.swing import VCSGisSwingLocator

def confirmDialog(prompt, title, optionType, messageType, msgid=None):
  manager = ToolsSwingLocator.getThreadSafeDialogsManager()
  n = manager.confirmDialog(prompt, title, optionType, messageType, msgid)
  return n

icons = dict()

def getIcon(name):
  icon = icons.get(name,None)
  if icon == None:
    pathname=getResource(__file__,"images", name + ".png")
    f = File(str(pathname))
    icon = ImageIcon(ImageIO.read(f))    
    icons[name] = icon
  return icon
 
class VCSGisWorkspaces(CatalogNode):
  def __init__(self, parent):
    CatalogNode.__init__(self,parent, icon=getIcon("workspaces"))
    self.__load()
    
  def __load(self,*args):
    self._children = list()
    descriptors_map = VCSGisLocator.getVCSGisManager().getWorkspaces()
    descriptors = list(descriptors_map.values())
    descriptors.sort(lambda x,y : cmp(x.getLabel().lower(),y.getLabel().lower()))
    for descriptor in descriptors:
        self._children.append(VCSGisWorkspace(self,  descriptor))
    self.reload()
    
  def toString(self):
    i18n = ToolsLocator.getI18nManager()
    return i18n.getTranslation("_VCSGis")

  def createPopup(self):
    i18n = ToolsLocator.getI18nManager()
    menu = JPopupMenu()
    menu.add(createJMenuItem(i18n.getTranslation("_Update"),self.__load))
    return menu    
   
class VCSGisWorkspace(CatalogNode):
  def __init__(self, parent, descriptor):
    CatalogNode.__init__(self, parent, icon=getIconFromParams(descriptor.getExplorerParameters()))
    self.__descriptor = descriptor
    self.__params = descriptor.getExplorerParameters()

  def getServerExplorer(self):
    return self.__descriptor.getExplorer()

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self,*args):
    self._children = list()
    self._children.append(VCSGisCategories(self, self.__descriptor))
    self._children.append(VCSGisModels(self, self.__descriptor))
    self._children.append(VCSGisResources(self, self.__descriptor))
    self._children.append(VCSGisTables(self, self.__descriptor))
    SwingUtilities.invokeLater(self.reload)
  
  def createPopup(self):
    i18n = ToolsLocator.getI18nManager()
    menu = JPopupMenu()
    menu.add(createJMenuItem(i18n.getTranslation("_Edit_parameters"),self.editParameters))
    menu.add(createJMenuItem(i18n.getTranslation("_Show_config"),lambda e: self.__showTable("VCSGIS_CONFIG")))
    menu.add(createJMenuItem(i18n.getTranslation("_Create_connexion"),lambda e: None, enabled=False))
    menu.add(JSeparator())
    menu.add(createJMenuItem(i18n.getTranslation("_Copy_URL"),self.copyURL))
    menu.add(JSeparator())
    menu.add(createJMenuItem(i18n.getTranslation("_Update"),self.__load))
    return menu    

  def __showTable(self, tablename):
    serverExplorer = self.__descriptor.getExplorer()
    params = serverExplorer.get(tablename)
    #openAsTable(params)
    #openAsForm(params)
    openSearchDialog(params)

  def editParameters(self, event=None):
    manager = DALSwingLocator.getDataStoreParametersPanelManager()
    panel = manager.createDataStoreParametersPanel(self.__params)
    manager.showPropertiesDialog(self.__params, panel)

  def copyURL(self, event=None):
    application = ApplicationLocator.getApplicationManager()
    url = self.__params.getDynValue("URL")
    if url.startswith("jdbc:h2:file:"):
      url = url.replace("jdbc:h2:file:","jdbc:h2:tcp://localhost:9123/")
    if url.startswith("jdbc:h2:split:"):
      url = url.replace("jdbc:h2:split:","jdbc:h2:tcp://localhost:9123/split:")
    application.putInClipboard(url)
    
  def toString(self):
    return  self.__descriptor.getLabel()

class VCSGisModels(CatalogNode):
  def __init__(self, parent, descriptor):
    CatalogNode.__init__(self, parent, icon=getIcon("modelos"))
    self.__descriptor = descriptor

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      for model in ws.getWorkspaceDataModels():
          self._children.append(VCSGisModel(self, self.__descriptor, model))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def toString(self):
    i18n = ToolsLocator.getI18nManager()
    return i18n.getTranslation("_Models")
    
class VCSGisModel(CatalogNode):
  def __init__(self, parent, descriptor, model):
    CatalogNode.__init__(self, parent, icon=getIcon("modelo"))
    self.__descriptor = descriptor
    self.__model = model

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      entities = ws.getWorkspaceEntities()
      entities.sort(lambda x,y : cmp(x.getLabel().lower(),y.getLabel().lower()))
      for entity in entities:
        if self.__model in entity.getDataModelsAsList():
          params = ws.createOpenStoreParameters(entity.getEntityName())
          self._children.append(VCSGisTable(self, params, entity, self.__descriptor))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def createPopup(self):
    i18n = ToolsLocator.getI18nManager()
    menu = JPopupMenu()
    menu.add(createJMenuItem(i18n.getTranslation("_VCS_Connect_to_datamodel"),lambda e:self.__connectToDataModel(),"tools-vcsgis-checkout-datamodel"))
    return menu    
  
  def __connectToDataModel(self):    
    PluginsLocator.getActionInfoManager().execute(
        "tools-vcsgis-checkout-datamodel", (
        "--workspace=", self.__descriptor.getWorkspace(),
        "--model=", self.__model
    ))
  
  def toString(self):
    return self.__model
    
class VCSGisResources(CatalogNode):
  def __init__(self, parent, descriptor):
    CatalogNode.__init__(self, parent, icon=getIcon("resources"))
    self.__descriptor = descriptor

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      for resource in ws.getWorkspaceResourcesTableNames():
          entity = ws.getWorkspaceEntity(resource)
          if entity != None:
            params = ws.createOpenStoreParameters(entity.getEntityName())
            self._children.append(VCSGisTable(self, params, entity, self.__descriptor))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def toString(self):
    i18n = ToolsLocator.getI18nManager()
    return i18n.getTranslation("_Resources")
        
class VCSGisCategories(CatalogNode):
  def __init__(self, parent, descriptor):
    CatalogNode.__init__(self, parent, icon=getIcon("tags"))
    self.__descriptor = descriptor

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      for category in ws.getWorkspaceEntityCategories():
          self._children.append(VCSGisCategory(self, self.__descriptor, category))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def toString(self):
    i18n = ToolsLocator.getI18nManager()
    return i18n.getTranslation("_Categories")

class VCSGisCategory(CatalogNode):
  def __init__(self, parent, descriptor, category):
    CatalogNode.__init__(self, parent, icon=getIcon("tag"))
    self.__descriptor = descriptor
    self.__category = category

  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      entities = ws.getWorkspaceEntities()
      entities.sort(lambda x,y : cmp(x.getLabel().lower(),y.getLabel().lower()))
      for entity in entities:
        if self.__category in entity.getCategoriesAsList():
          params = ws.createOpenStoreParameters(entity.getEntityName())
          self._children.append(VCSGisTable(self, params, entity, self.__descriptor))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def toString(self):
    return  self.__category

class VCSGisTables(CatalogNode):
  def __init__(self, parent, descriptor):
    CatalogNode.__init__(self, parent, icon=getIcon("tables"))
    self.__descriptor = descriptor
 
  def _getChildren(self):
    if self._children == None:
      self.__load()
    return self._children
    
  def __load(self):
    self._children = list()
    try :
      ws = self.__descriptor.getWorkspace()
      entities = ws.getWorkspaceEntities()
      entities.sort(lambda x,y : cmp(x.getLabel().lower(),y.getLabel().lower()))
      for entity in entities:
          params = ws.createOpenStoreParameters(entity.getEntityName())
          self._children.append(VCSGisTable(self, params, entity, self.__descriptor))
    except Throwable as e:
      e.printStackTrace()
      pass
    finally:
      DisposeUtils.disposeQuietly(ws)
    SwingUtilities.invokeLater(self.reload)

  def toString(self):
    i18n = ToolsLocator.getI18nManager()
    return i18n.getTranslation("_Tables")


class VCSGisTable(CatalogSimpleNode):
  def __init__(self, parent, params, entity, wsdescriptor):
    CatalogSimpleNode.__init__(self, parent, icon=getIcon("table"))
    self.__entity = entity
    self.__params = params
    self.__wsdescriptor = wsdescriptor
  
  def getParams(self):
    return self.__params
        
  def toString(self):
    return self.__entity.getLabel()
    
  def createPopup(self):
    i18n = ToolsLocator.getI18nManager()
    menu = JPopupMenu()
    menu.add(createJMenuItem(i18n.getTranslation("_Add_to_view"),self.actionPerformed, "view-layer-add"))
    menu.add(createJMenuItem(i18n.getTranslation("_Open_as_table"),self.openAsTable, "layer-show-attributes-table"))
    menu.add(createJMenuItem(i18n.getTranslation("_Open_as_form"),self.openAsForm, "layer-show-form"))
    menu.add(createJMenuItem(i18n.getTranslation("_Open_search_dialog"),self.openSearchDialog, "search-by-attributes-layer"))
    menu.add(JSeparator())
    menu.add(createJMenuItem(i18n.getTranslation("_Add_to_bookmarks"),self.addToBookmarks))
    menu.add(JSeparator())
    menu.add(createJMenuItem(i18n.getTranslation("_Remove_entity"),self.removeEntity))
    menu.add(createJMenuItem(i18n.getTranslation("_Edit_parameters"),self.editParameters))
    menu.add(JSeparator())
    menu.add(createJMenuItem(i18n.getTranslation("_VCS_Checkout"),lambda e:self.__showCheckout(), "tools-vcsgis-checkout"))
    menu.add(createJMenuItem(i18n.getTranslation("_VCS_Show_changes"),lambda e:self.__showChanges(), "tools-vcsgis-showchanges"))
    actions = getCatalogManager().getActions("VCSGIS_TABLE", self.__params)
    if len(actions)>0 :
      menu.add(JSeparator())
      for action in actions:
        menu.add(JMenuItem(action))
    return menu    

  def __showCheckout(self):
    PluginsLocator.getActionInfoManager().execute(
        "tools-vcsgis-checkout", (
        "--workspace=", self.__wsdescriptor.getWorkspace(),
        "--tablenames=", (self.__entity.getEntityName(),),
        "--overwrite=", True
    ))
  
  def __showChanges(self):
    PluginsLocator.getActionInfoManager().execute(
        "tools-vcsgis-showchanges", (
        "--workspace=", self.__wsdescriptor.getWorkspace(),
        "--tablenames=", (self.__entity.getEntityName(),),
    ))

  def removeEntity(self, *args):
    ws = self.__wsdescriptor.getWorkspace()
    ws.removeEntity(self.__entity.getEntityName())
    self.reload()

  def openAsForm(self, *args):
    openAsForm(self.getParams())

  def openSearchDialog(self, *args):
    #menu.add(createJMenuItem(i18n.getTranslation("_Open_search_dialog"),self.openSearchDialog))
    openSearchDialog(self.getParams())
    
  def addToBookmarks(self, event=None):
    addToBookmarks(self.getRoot(), self.getParams(), self.__entity.getLabel())

  def openAsTable(self, event):
    openAsTable(self.getParams(), self.__entity.getLabel())
  
  def editParameters(self, event):
    openAsParameters(self.getParams())
  
  def actionPerformed(self, event):
    openAsLayer(self.getParams(), self.__entity.getLabel())

def selfRegister(*args):
  catalogManager = getCatalogManager()
  catalogManager.addCatalogNode(VCSGisWorkspaces)
  catalogManager.putCatalogInViews()

    
def main(*args):
  selfRegister()
  pass
