# Copyright (C) 2017 VMware, Inc.  All rights reserved.
# -- VMware Confidential

import logging
import vcsa_utils
from extensions import extend, Hook
from l10n import msgMetadata as _T, localizedString as _
from reporting import getProgressReporter

import sys
from os.path import dirname, realpath, join

payloadDir = dirname(realpath(__file__))
patchesDir = join(payloadDir, "patches")

sys.path.append(payloadDir)
sys.path.append(patchesDir)


logger = logging.getLogger(__name__)

import utils


@extend(Hook.Discovery)
def discover(ctx):
    "DiscoveryResult discover(PatchContext ctx) throw UserError"

    logger.info("Reverse HTTP Proxy Extension Discovery Hook")

    return vcsa_utils.getComponentDiscoveryResult(
        "rhttpproxy", displayName=_(_T("rhttpproxy.b2b.patch.name",
                                       "VMware vCenter Reverse HTTP Proxy")))


def _doIncrementalPatching(ctx):
    currVersion = getCurrentVersion()
    patchCurrentVersion = currVersion is None

    for ver, modulePath in patches:
        patchCurrentVersion |= currVersion == ver

        if patchCurrentVersion:
            logger.info("Applying patch {0} on version {1}".format(modulePath,
                                                                   ver))
            mod = __import__(modulePath)
            mod.doPatching(ctx)
            logger.info("Patch {0} applied".format(modulePath))

    utils.setSourceVersion(getLatestVersion())


patches = [
    ("6.6.0.1", "patch01"),
]


def getCurrentVersion():
    return utils.getSourceVersion()


def getLatestVersion():
    return patches[-1][0]


@extend(Hook.Patch)
def patch(ctx):
    "void patch(PatchContext ctx) throw UserError"

    logger.info("Reverse HTTP Proxy Extension Patch Hook")
    progressReporter = getProgressReporter()

    progressReporter.updateProgress(0)
    _doIncrementalPatching(ctx)
    progressReporter.updateProgress(100)
