package com.eactive.eai.rms.data.entity.man.user;

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

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class UserRoleService extends AbstractEMSDataSerivce<UserRole, UserRoleId, UserRoleRepository> {

	public String getRoleId(String empno) {
		QUserRole qUserRole = QUserRole.userRole;
		return repository.findOne(qUserRole.id.userId.eq(empno))
				.map(userRole -> userRole.getId().getRoleId())
				.orElse(null);
	}

   public void deleteAllByUserId(String userId) {
	      repository.deleteAll(findByUserId(userId));
	   }

	public List<UserRole> findByUserId(String userId) {
		QUserRole qUserRole = QUserRole.userRole;
		List<UserRole> list = new ArrayList<>();
		repository.findAll(qUserRole.id.userId.eq(userId)).forEach(list::add);
		return list;
	}

	public void deleteOrSave(String userId, List<UserRole> userRoles) {
		List<UserRole> existUserRoles = findByUserId(userId);
		existUserRoles.removeAll(userRoles);
		deleteAll(existUserRoles);
		
		userRoles.stream().forEach(userRole -> {
			if (!existsById(userRole.getId())) {
				repository.save(userRole);
			}
		});
	}

}

