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.StoreServiceException;
import com.prime.sony.ecommerce.model.JobInformation;

//@Component
@Configuration
public class StoreServiceJob {

	private static final Logger log = LoggerFactory.getLogger(StoreServiceJob.class);

	
	@Autowired
	JobLauncher jobLauncher;
	
	@Autowired
	Job job;
	
	@Autowired
	private JobInformation jobInformation;
	
	@Scheduled(cron="#{@getCronValue}")
	public void saveStoreDataScheduler() throws Exception {
		
		log.info("==>StoreServiceJob.saveStoreDataScheduler()");
		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 StoreServiceJob.saveStoreDataScheduler()",e);
			
			throw new StoreServiceException(e.getMessage(), e.getCause(), null);
		}
		log.info("<==StoreServiceJob.saveStoreDataScheduler()");
	}
	
	

}
