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

import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.common.seed.Seed;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.util.CommonConstants;
import com.eactive.apim.portal.user.entity.UserInfo;
import com.eactive.eai.rms.data.entity.man.user.UserInfoService;
import com.eactive.eai.rms.data.entity.man.user.UserRole;
import com.eactive.eai.rms.data.entity.man.user.UserRoleId;
import com.eactive.eai.rms.data.entity.man.user.UserRoleService;
import com.eactive.eai.rms.data.entity.man.user.UserServiceType;
import com.eactive.eai.rms.data.entity.man.user.UserServiceTypeId;
import com.eactive.eai.rms.data.entity.man.user.UserServiceTypeService;
import com.eactive.eai.rms.data.entity.onl.bzwkdstcd.UserBusinessService;
import com.eactive.ext.djb.DamoManager;

@Service
@Transactional
public class UserSyncService extends BaseService {

	private UserDao userDao;
	private UserInfoService userInfoService;
	private UserRoleService userRoleService;
	private UserServiceTypeService userServiceTypeService;
	private UserBusinessService userBusinessService;
	private UserManService userManService;

	@Autowired
	public UserSyncService(UserDao userDao, UserInfoService userInfoService, UserRoleService userRoleService,
			UserServiceTypeService userServiceTypeService, UserBusinessService userBusinessService,
			UserManService userManService) {
		this.userDao = userDao;
		this.userInfoService = userInfoService;
		this.userRoleService = userRoleService;
		this.userServiceTypeService = userServiceTypeService;
		this.userBusinessService = userBusinessService;
		this.userManService = userManService;
	}

	public List<HashMap<String, Object>> selectSyncUser(String iimSchemaId) {
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("schemaId", iimSchemaId);
		return userDao.selectCompanyList(paramMap);
	}

	public List<HashMap<String, Object>> selectDeleteSyncUser(String iimSchemaId) {
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("schemaId", iimSchemaId);
		return userDao.selectDeleteCompanyList(paramMap);
	}

	public void saveUsers(List<HashMap<String, Object>> syncInsertUserList) throws Exception {

		Set<String> existUserIds = userInfoService.findAll().stream()
				.map(UserInfo::getUserid)
				.collect(Collectors.toSet());

		List<HashMap<String, Object>> newUsers = syncInsertUserList.stream()
				.filter(user -> !existUserIds.contains(user.get("EMPNO").toString()))
				.collect(Collectors.toList());

		if (newUsers.size() > 0) {
			saveUser(newUsers);
		}

	}

	public void deleteUsers(List<HashMap<String, Object>> syncDeleteUserList) {
		Set<String> deleteUsers = syncDeleteUserList.stream()
				.map(e -> e.get("EMPNO").toString())
				.collect(Collectors.toSet());
		
		for (String userId : deleteUsers) {
			
			try {
				
				if (userInfoService.existsById(userId)) {					
					userInfoService.deleteById(userId);
				}

				userRoleService.deleteAllByUserId(userId);
				userServiceTypeService.deleteAllByUserId(userId);
				
				userManService.insertUserAthrRoleChgHistory(userId, CommonConstants.CHANGE_TYPE_ROLE, 
						"DELETE USER", 
						CommonConstants.SYSTEM,
						"127.0.0.1");				

			} catch (Exception e) {
				logger.error("user delete failed : " + userId);
			}

		}
	}

	/* APIGW DataSourceType */
	public void deleteBusinessUser(List<HashMap<String, Object>> syncDeleteUserList) {
		Set<String> deleteUsers = syncDeleteUserList.stream()
				.map(e -> e.get("EMPNO").toString())
				.collect(Collectors.toSet());

		for (String userId : deleteUsers) {
			// 업무 권한이 있는경우 삭제
			if (userBusinessService.existByUserId(userId)) {
				userBusinessService.deleteAllByUserId(userId);
			}
		}
	}

	private void saveUser(List<HashMap<String, Object>> newUsers) throws Exception {
		
		for (HashMap<String, Object> userInfoMap : newUsers) {

			String userId = (String) userInfoMap.get("EMPNO");

			UserInfo userInfo = new UserInfo();
			userInfo.setUserid(userId);
			userInfo.setUsername(userInfoMap.get("EMPY_NM").toString());
			userInfo.setPassword(DamoManager.getInstance().hash(DamoManager.SHA256,userId));
			userInfo.setRoleidnfiname(CommonConstants.DEPT_DEVELOPER);

			userInfoService.save(userInfo);

			UserRoleId roleId = new UserRoleId(userId, CommonConstants.DEPT_DEVELOPER);
			
			if (!userRoleService.existsById(roleId)) {
				UserRole userRole = new UserRole();
				userRole.setId(roleId);
				userRoleService.save(userRole);
			}
			
			UserServiceTypeId typeId = new UserServiceTypeId(userId, CommonConstants.USER_SERVICE_TYPE_APIGW);

			if (!userServiceTypeService.existsById(typeId)) {
				UserServiceType userServiceType = new UserServiceType();
				userServiceType.setId(typeId);
				userServiceTypeService.save(userServiceType);
			}

			userManService.insertUserAthrRoleChgHistory(userId, CommonConstants.CHANGE_TYPE_ROLE, 
					"NEW USER :" + CommonConstants.DEPT_DEVELOPER, 
					CommonConstants.SYSTEM,
					"127.0.0.1");
			
		}
	}


}
