from .VmomiSupport import nsMap, versionMap, versionIdMap, serviceNsMap, parentMap

sInternal = "internal"

def AddVersionInt(version, ns, versionId, isLegacy, serviceNs):
  if not ns:
     ns = serviceNs
  if not (version in parentMap):
      nsMap[version] = ns
      if len(versionId) > 0:
         versionMap[ns + '/' + versionId] = version
      if isLegacy or ns is "":
         versionMap[ns] = version
      versionIdMap[version] = versionId
      if not serviceNs:
         serviceNs = ns
      serviceNsMap[version] = serviceNs
      parentMap[version] = {}

## Add an API version
def AddVersion(version, ns, versionId='', isLegacy=0, serviceNs=''):
   AddVersionInt(version, ns, versionId, isLegacy, serviceNs)
   internalVersion = GetInternalVersion(version)
   internalServiceNs = sInternal + serviceNs if serviceNs else ''
   internalNs = sInternal + ns if ns else ''
   AddVersionInt(internalVersion, internalNs, versionId, isLegacy, internalServiceNs)

## Get internal version string from the public version string
# vim.version.version7 --> vim.version.internalversion7
def GetInternalVersion(version):
   versions = version.rsplit(".", 1)
   return ".".join([versions[0], sInternal + versions[1]])

## Returns public version from an internal version. In case of public version,
#  it returns the same string
def GetPublicVersion(version):
   return "".join(version.split("internal"))

## Check if a version is a child of another
def IsChildVersion(child, parent):
   return child == parent or GetPublicVersion(parent) in parentMap[GetPublicVersion(child)]
