# Copyright 2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#
'''
Holder of some handy functions which are being used across all the phases in
the resumabilty context
'''
from vmware_b2b.patching.utils.reporting_utils import createComponentReportingIdentifier

def updateAndSavePhaseContext(ctx, executionContext, component=None):
    '''Saves the state of the context while

    @param ctx: Patch context which is being persisted in the stageDir
    @type ctx: PatchPhaseContext

    @param executionContext: Context of the execution
    @type executionContext: executionContext


    @param component:Name of the components whose execution is completed
    @type component: str
    '''
    executionContext.executed(component)
    ctx.persist(ctx.stageDir)

def calculateCompletedComponentsForRepoting(ctx, *hooks):
    ''' Calculates reporting identifiers for the purpose of reporting for the
    already completed components for the given hook. It does that only for the
    patchable components and uses ctx for that purpose.

    @param ctx: Patch context which is being persisted in the stageDir
    @type ctx: PatchPhaseContext

    @param hooks: List of hooks to get execution context from the
    @type ctx: PatchPhaseContext

    @return: List of string that are the completed reporters for the asked hooks.
    Example: ["a:Patch", "b:Patch", "a:OnSuccess"]
    '''
    identifiers = []
    for hook in hooks:
        execContext = ctx.getPhaseExecution(hook)
        if not execContext.isStarted():
            continue
        for c in ctx.getPatchableComponents():
            if execContext.isComponentExecuted(c.name):
                identifiers.append(createComponentReportingIdentifier(c, hook))
    return identifiers
