# Copyright 2020 VMware, Inc.  All rights reserved. -- VMware Confidential
#
'''
Script responsible to setup environment and execute the Contract hook of vCSA
components. The script calls only those components which have been discovered
in prior discovery phase.
'''

import logging
from extensions import Hook

from vmware_b2b.patching.utils.phase_utils import executeHook, setupStatusAggregator
from vmware_b2b.patching.data.model import PatchPhaseContext
from vmware_b2b.patching.phases.patcher import _runOnSuccess

logger = logging.getLogger(__name__)


def contract(stageDir, userData, outputFile):
    '''The entry point of contract CPO phase.

    The Contract phase is responsible to setup the environment and execute the
    contract hook of vCSA components. The contract hook is executed only
    on those components which have been discovered in prior discovery phase.

    @param stageDir: global CPO stage directory. All components stage
      directories will be created as sub-directories of global stage directory.
    @type stageDir: str

    @param userData: Customer input, as result of component questions raised
      in @Discovery patching hook.
    @type userData: dict

    @param outputFile: File where the output of the command needs to be written
      to
    @type outputFile: str

    @return: True if the Contract phase succeed and False otherwise
    @rtype: bool
    '''
    ctx = PatchPhaseContext.load(stageDir)
    hooks = [Hook.Contract, Hook.OnSuccess]

    with setupStatusAggregator(ctx, outputFile, hooks) as statusAggregator:
        logger.info("Running %s phase", Hook.Contract)
        if not executeHook(Hook.Contract, ctx, userData, statusAggregator):
            return False

        logger.info("Running %s phase", Hook.OnSuccess)
        _runOnSuccess(ctx, userData, statusAggregator.reportingQueue)

    return True

