package com.eactive.eai.rms.common.acl.user;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;

public class UserAccountLockJob  implements Job {
	
private static final Logger logger = Logger.getLogger(UserAccountLockJob.class);
	
	private UserAccountLockService userAccountLockService;
	
	@Autowired
	public UserAccountLockJob(UserAccountLockService userAccountLockService) {
		this.userAccountLockService=userAccountLockService;
	}
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		if (logger.isInfoEnabled()) logger.info("START USER ACCOUNT LOCK JOB");
		
		ApplicationContext appContext = null;
		
		try {
			appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error", e);
			return;
		}
		
		userAccountLockService=(UserAccountLockService)appContext.getBean("userAccountLockService");
		
		// APIMS USER ACCCOUNT LOCK		
		try {
			logger.info("START USER ACCOUNT LOCK SERVICE SCHECULER ...");
			
			DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
			DataSourceContextHolder.setDataSourceType(dataSourceType);
						
			userAccountLockService.updateUserAccountLock(dataSourceType.getSchema());			
			
		} catch (Exception e) {
			logger.error("USER ACCOUNT LOCK SERVICE ERROR",e);
		}
		
		if (logger.isInfoEnabled()) logger.info("PORTAL USER ACCOUNT LOCK JOB");
		
		// API PORTAL USER ACCCOUNT LOCK		
		try {
			logger.info("START PORTAL USER ACCOUNT LOCK SERVICE SCHECULER ...");
			
			DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
			DataSourceContextHolder.setDataSourceType(dataSourceType);
						
			userAccountLockService.updatePortalUserAccountLock(dataSourceType.getSchema());			
			
		} catch (Exception e) {
			logger.error("USER ACCOUNT LOCK SERVICE ERROR",e);
		}
		
		if (logger.isInfoEnabled()) logger.info("END USER ACCOUNT LOCK JOB");
		
	}

}
