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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eactive.eai.rms.common.acl.role.RoleUI;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import com.querydsl.core.types.dsl.BooleanExpression;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class RoleService extends AbstractEMSDataSerivce<Role, String, RoleRepository> {

	public List<String> getRoleScreenId(List<String> roleIds) {
		QRole qRole = QRole.role;
		BooleanExpression predicate = qRole.roleId.in(roleIds);
		Iterable<Role> roles = repository.findAll(predicate, Sort.by(Sort.Direction.DESC, "menuId"));
		return StreamSupport.stream(roles.spliterator(), false).map(Role::getMenuId).collect(Collectors.toList());
	}

	public Page<Role> findAll(Pageable pageable, RoleUI roleUI) {
		QRole qRole = QRole.role;

		BooleanExpression predicate = qRole.roleId.containsIgnoreCase(roleUI.getSearchRoleId());

		if (StringUtils.isNotBlank(roleUI.getSearchRoleName())) {
			predicate = predicate.and(qRole.roleName.containsIgnoreCase(roleUI.getSearchRoleName()));
		}
		if (StringUtils.isNotBlank(roleUI.getSearchUseYn())) {
			predicate = predicate.and(qRole.useYn.eq(roleUI.getSearchUseYn()));
		}

		return repository.findAll(predicate, pageable);
	}

	public List<Map<String, Object>> selectRole(String searchUseYn) {
		List<Map<String, Object>> roleMaps = new ArrayList<>();

		findAllRolesByUseYn(searchUseYn).forEach(role -> {
			Map<String, Object> map = new HashMap<>();
			map.put("ROLEID", role.getRoleId());
			map.put("ROLENAME", role.getRoleName());
			roleMaps.add(map);
		});
		return roleMaps;
	}

	public Iterable<Role> findAllRolesByUseYn(String useStatus) {
		return repository.findAll(QRole.role.useYn.containsIgnoreCase(useStatus));
	}

}
