package com.prime.sony.ecommerce.tasklets;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.prime.sony.ecommerce.exceptions.ProductServiceException;
import com.prime.sony.ecommerce.model.ExceptionMessage;
import com.prime.sony.ecommerce.service.ProductService;

@Service
public class MyTaskOne implements Tasklet {

	private static final Logger log = LoggerFactory.getLogger(MyTaskOne.class);

	@Autowired
	private ProductService productService;

	@Autowired
	private ExceptionMessage exceptionMessage;

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext)
			throws ProductServiceException {
		log.info("==>MyTaskOne.execute()");
		try {
			Map<String, String> resultMap = productService.saveProductData();
			chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("RESULT_MAP",
					resultMap);

			exceptionMessage.setServiceExceptionMessage(null);
		} catch (Exception e) {
			log.error("==> Exception at MyTaskOne.execute()", e);
			exceptionMessage.setServiceExceptionMessage(e.getMessage());
			throw new ProductServiceException(e.getMessage(), e.getCause(), null);
		}

		log.info("<==MyTaskOne.execute()");
		return RepeatStatus.FINISHED;
	}

}
