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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.prime.sony.ecommerce.exceptions.CustomerServiceException;
import com.prime.sony.ecommerce.model.JobInformation;

@Service
public class CustomerServiceJob {

	private static final Logger log = LoggerFactory.getLogger(CustomerServiceJob.class);

	@Autowired
	JobLauncher jobLauncher;

	@Autowired
	Job job;
	
	@Autowired
	private JobInformation jobInformation;
	
	

	@Scheduled(cron="#{@getCronValue}")
	public void saveCustomerDataScheduler() throws Exception {

		log.info("==>CustomerServiceJob.saveCustomerDataScheduler()");
		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 CustomerServiceJob.saveCustomerDataScheduler()", e);
			throw new CustomerServiceException(e.getMessage(), e.getCause(), null);
		}
		log.info("<==CustomerServiceJob.saveCustomerDataScheduler()");
		
	}

}
