package com.prime.sony.ecommerce.jobs;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import com.prime.sony.ecommerce.exceptions.ProductServiceException;
import com.prime.sony.ecommerce.model.JobInformation;

//@Component
@Configuration
public class ProductServiceJob {

	private static final Logger log = LoggerFactory.getLogger(ProductServiceJob.class);

	@Autowired
	JobLauncher jobLauncher;

	@Autowired
	Job job;

	@Autowired
	private JobInformation jobInformation;

	@Scheduled(cron = "#{@getCronValue}")
	public void saveProductDataScheduler() throws Exception {

		log.info("==>ProductServiceJob.saveProductDataScheduler()");
		try {
			JobParameters params = new JobParametersBuilder()
					.addString("JobID", String.valueOf(System.currentTimeMillis())).toJobParameters();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String jobStartTime = format.format(new Date().getTime());
			jobInformation.setSchedulerExecutionTime(jobStartTime);
			jobLauncher.run(job, params);
		} catch (Exception e) {
			log.error("==> Exception at ProductServiceJob.saveProductDataScheduler()", e);
			throw new ProductServiceException(e.getMessage(), e.getCause(), null);
		}
		log.info("<==ProductServiceJob.saveProductDataScheduler()");
		// throw new Exception();
	}

}
