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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

import com.eactive.eai.rms.common.acl.user.BizManService;
import com.eactive.eai.rms.common.acl.user.UserManService;
import com.eactive.eai.rms.common.acl.user.ui.UserBizUI;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;

public class BizCodeRoleMappingJob implements Job {

	private static final Logger logger = Logger.getLogger(BizCodeRoleMappingJob.class);

	private BizManService bizManService;

	private UserManService userManService;

	@Autowired
	public BizCodeRoleMappingJob(BizManService bizManService, UserManService userManService) {
		this.bizManService = bizManService;
		this.userManService = userManService;
	}

	// TSEAICM01 업무코드 ADMIN USER 권한부여
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		if (logger.isInfoEnabled())
			logger.info("START BizCodeRoleMappingJob");

		List<Map<String, Object>> adminUserList = new ArrayList<>();

		try {
			// 모니터링 TSEAIRM02,04 admin 계정 USERID 배열 만들기
			adminUserList = userManService.selectAdminRoleUser("admin");
		} catch (Exception e) {
			logger.error("Error retrieving admin user list: ", e);
			return;
		}

		// INST별 for 문 실행
		for (DataSourceType d : DataSourceTypeManager.getDynamicDataSourceTypes()) {
			if ("MONITORING".equals(d.getName()) || "META".equals(d.getName())) {
				continue;
			}
			logger.info("DataSourceTypeManager d : " + d);

			for (Map<String, Object> userMap : adminUserList) {
				processUser(d, userMap);
			}
		}
		logger.info("END BizCodeRoleMappingJob");
	}

	private void processUser(DataSourceType dataSourceType, Map<String, Object> userMap) {
		UserBizUI userBizUI = new UserBizUI();
		userBizUI.setUserId(String.valueOf(userMap.get("USERID")));
		userBizUI.setSearchBzwkName("");
		userBizUI.setTargetGridYn("N");

		List<UserBizUI> bizList = bizManService.selectUserBizList(userBizUI);

		for (UserBizUI bizTmp : bizList) {
			if (logger.isInfoEnabled()) {
				logger.info("serverType : " + dataSourceType.getName() + " ,admin bizCode ==>" + bizTmp);
			}

			UserBizUI ui = new UserBizUI();
			ui.setUserId(bizTmp.getUserId());
			ui.setBizCode(bizTmp.getBizCode());

			try {
				bizManService.insertUserBiz(ui, "R");
			} catch (Exception e) {
				logger.warn("admin role TSEAIRM06 bizCode insert failed", e);
			}
		}
	}

}
