package com.javahonk;

import java.time.LocalDateTime;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Java Honk
 *
 */
public class CronQuartzJob implements Job {
	
	@Value("${cron.schedule.time}")
	private String cronScheduleTime;
	
	private static final Logger LOGGER = LogManager.getLogger(CronQuartzJob.class.getName());
	
	public static void main(String[] args) {
		
		LOGGER.info("CronQuartzJob started.");	
		
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		
		CronQuartzJob cronQuartzJob = (CronQuartzJob)context.getBean(CronQuartzJob.class);
		cronQuartzJob.startJavaHonkQuartzJob();
		
		((AbstractApplicationContext)context).close();
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		
		LOGGER.info("Cron Quartz Job started at time: {}", LocalDateTime.now());
		System.out.println("Cron Quartz Job started at time: "+ LocalDateTime.now());

	}
	
	public void startJavaHonkQuartzJob() {

		try {

			JobDetail job = JobBuilder.newJob(CronQuartzJob.class).withIdentity("Java Honk Price Update", "Java Honk Data Cache").build();
			
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity("Java Honk Price Update", "Java Honk Data Cache")
					.withSchedule(CronScheduleBuilder.cronSchedule(cronScheduleTime)).build();

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.start();
			scheduler.scheduleJob(job, trigger);
			
		} catch (SchedulerException e) {
			LOGGER.error("Exception occured class name:-> "+ CronQuartzJob.class.getName()+ "method: startJavaHonkQuartzJob:-->{}", e);
		}

	}	

}
