package com.eactive.eai.rms.bat.common.service;

import java.time.Period;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.util.TypeCastUtils;
import com.eactive.eai.rms.common.util.TypeCastUtils.TypeCastException;

public class BatLogTableDeleteJob2 implements Job {

	private static final Logger logger = Logger.getLogger(BatLogTableDeleteJob2.class);
	private final String logPrefix = BatLogTableDeleteJob2.class.getSimpleName() + "] ";

	private static final String defaultRemainPeriodDays = "7";

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		try {
			
			ApplicationContext applicationContext = 
					TypeCastUtils.cast(context.getScheduler().getContext().getOrDefault("applicationContext", null), ApplicationContext.class);
			
			BatLogTableDeleteService service = 
					TypeCastUtils.cast(applicationContext.getBean(BatLogTableDeleteService.class), BatLogTableDeleteService.class);
			
			String remain = 
					TypeCastUtils.castOrElse(context.getJobDetail().getJobDataMap().get("remainPeriod"), String.class, defaultRemainPeriodDays);
			
			int remainInt = Integer.parseInt(remain);
			
			
			DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAT));
			
			logger.info(logPrefix + " START]----------");
			
			int deletedRows = service.delete(Period.ofDays(remainInt));
			
			logger.info(logPrefix + "] deleted rows : " + deletedRows);
			
			
			
		} catch (TypeCastException te) {
			logger.error(te.getMessage(), te);
		} catch (SchedulerException se) {
			logger.error(se.getMessage(), se);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			logger.info(logPrefix + " END]----------");
		}
		
	}
}