#
# Copyright 2018 VMware, Inc.  All rights reserved. -- VMware Confidential
#
"""PatchRunner integration hook for topologysvc Service

This module integrates topologysvc patching scripts with the
PatchRunner Framework.

"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2018 VMware, Inc. All rights reserved.'

import logging
import os
import sys

from extensions import extend, Hook
from fss_utils import getTargetFSS
from l10n import msgMetadata as _T, localizedString as _
from patch_specs import ValidationResult, Question, Mismatch, Requirements, \
    PatchInfo, RequirementsResult
from reporting import getProgressReporter
from . import utils
import vcsa_utils

sys.path.append(os.path.join(os.path.dirname(__file__), "patches"))
patches = [
    # In order to update from version 0 to version 1, execute patch_01.py
    ("1","patch_01"),
]

COMPONENT_NAME = "topologysvc"

logger = logging.getLogger(__name__)

@extend(Hook.Discovery)
def discover(patch_context):
    logger.info("Executing Discovery Hook for topologysvc Service")

    if not getTargetFSS("TopologySvc"):
        logger.info("topologysvc.patch: TopologySvc not enabled on target build")
        return None

    return vcsa_utils.getComponentDiscoveryResult(COMPONENT_NAME,
                                                  displayName=_(
                                                   _T("topologysvc.displayName",
                                                   "Topology Service")))


@extend(Hook.Patch)
def execute_patch(patch_context):
    #This hook is invoked after the rpms are installed.
    logger.info("Executing Patch Hook for topologysvc Service")
    progressReporter = getProgressReporter()
    progressReporter.updateProgress(0, _(_T("topologysvc.patch.begin",
                                            "Start topologysvc patching")))
    _do_incremental_patching(patch_context)
    progressReporter.updateProgress(100, _(_T("topologysvc.patch.complete",
                                              "Patching topologysvc completed")))

def _do_incremental_patching(ctx):
    for ver, modulePath in patches:
        logger.info("Checking if need patch %s on version %s"
                     % (ver, modulePath))
        mod = __import__(modulePath)

        if utils.is_patch_needed(ver):
            logger.info("Patch %s needed" % (modulePath))
            mod.doPatching(ctx)
            logger.info('Patch %s applied' % (modulePath))

            utils.update_patch_version(ver)
