/*
 * 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.sdm.config.spring.batch.listeners;

import static java.text.MessageFormat.format;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.scytl.products.ov.config.commands.voters.JobExecutionObjectContext;
import com.scytl.products.ov.sdm.config.spring.batch.VotingCardGenerationJobExecutionContext;


public class VotingCardGenerationJobListener implements JobExecutionListener {

    private static final Logger LOG = LoggerFactory.getLogger("std");

    @Autowired
    private JobExecutionObjectContext stepExecutionObjectContext;

    @Override
    public void beforeJob(final JobExecution jobExecution) {
        final VotingCardGenerationJobExecutionContext jobExecutionContext = new
            VotingCardGenerationJobExecutionContext(jobExecution.getExecutionContext());

        //init counters
        jobExecutionContext.setGeneratedCardCount(0);
        jobExecutionContext.setErrorCount(0);

    }

    @Override
    public void afterJob(final JobExecution jobExecution) {
        final VotingCardGenerationJobExecutionContext jobExecutionContext = new
            VotingCardGenerationJobExecutionContext(jobExecution.getExecutionContext());

        //clear all temporary data related to this job
        final String jobInstanceId = jobExecutionContext.getJobInstanceId();
        //the job may fail right away and so the context can be empty. just a precaution to avoid nullptr
        if(jobInstanceId != null) {
            stepExecutionObjectContext.removeAll(jobInstanceId);
        }

        if(ExitStatus.COMPLETED.equals(jobExecution.getExitStatus())) {

            final double generatedCount = jobExecutionContext.getGeneratedCardCount();
            final int errorCount = jobExecutionContext.getErrorCount();

            LOG.info("Job [{}] completed. Results: [voting cards generated={}, errors={}]", jobInstanceId,
                generatedCount, errorCount);

        } else {
            LOG.warn("Job [{}] failed with the exit status: {}", jobInstanceId, jobExecution.getExitStatus());
            for (Throwable e : jobExecution.getAllFailureExceptions()) {
                LOG.warn(format("Job [{0}] failed because of error:", jobInstanceId), e);
            }
        }

    }
}
