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

import java.util.HashMap;
import java.util.List;

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 UserSyncJob implements Job {
	private static final Logger logger = Logger.getLogger(UserSyncJob.class);

	private UserSyncService userSyncService;

	@Autowired
	public UserSyncJob(UserSyncService userSyncService) {
		this.userSyncService = userSyncService;
	}
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {

		if (logger.isInfoEnabled()) logger.info("START USERSYNCJOB");

		ApplicationContext appContext = null;
		try {
			appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
		} catch (SchedulerException e) {
			logger.error("applicationContext get module error", e);
			return;
		}

		userSyncService = (UserSyncService) appContext.getBean("userSyncService");

		try {
			logger.info("START USERSYNCJOB_SCHEDULER...");


			DataSourceType dataSourceType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.IM);
			DataSourceContextHolder.setDataSourceType(dataSourceType);

			List<HashMap<String, Object>> syncUserList = userSyncService.selectSyncUser(dataSourceType.getSchema());
			List<HashMap<String, Object>> syncDeleteUserList = userSyncService.selectDeleteSyncUser(dataSourceType.getSchema());

			logger.info("START saveUsers deleteUsers ...");

			/* DataSourceType 변경 - MONITORING */
			dataSourceType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.MONITORING);
			DataSourceContextHolder.setDataSourceType(dataSourceType);

			if(syncUserList.size() > 0) {
				userSyncService.saveUsers(syncUserList);
			}
			
			if(syncDeleteUserList.size() > 0) {
				userSyncService.deleteUsers(syncDeleteUserList);
			}

			/* DataSourceType 변경 - APIGW */
			if(syncDeleteUserList.size() > 0) {
				
				dataSourceType = DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.APIGW);
				DataSourceContextHolder.setDataSourceType(dataSourceType);
				userSyncService.deleteBusinessUser(syncDeleteUserList);
			}

		} catch (Exception e) {
			logger.error("USERSYNCJOB ERROR ", e);
		}

	}

}
