/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.validation.spring.batch;

import org.springframework.batch.core.scope.context.JobContext;
import org.springframework.batch.core.scope.context.JobSynchronizationManager;
import org.springframework.core.task.TaskDecorator;

import com.scytl.products.oscore.logging.core.provider.TransactionInfoProvider;

/**
 * Implementation of {@link TaskDecorator} which allows to run the supplied step
 * task in appropriate context.
 */
class StepTaskDecorator implements TaskDecorator {
    private final TransactionInfoProvider provider;

    private final String tenantId;

    /**
     * Constructor.
     *
     * @param provider
     * @param tenantId
     */
    public StepTaskDecorator(final TransactionInfoProvider provider,
            final String tenantId) {
        this.provider = provider;
        this.tenantId = tenantId;
    }

    @Override
    public Runnable decorate(final Runnable task) {
        JobContext context = JobSynchronizationManager.getContext();
        return () -> runTask(task, context);
    }

    private void runTask(final Runnable task, final JobContext context) {
        JobSynchronizationManager.register(context.getJobExecution());
        try {
            provider.generate(tenantId, "", "");
            task.run();
        } finally {
            JobSynchronizationManager.close();
        }
    }
}
