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

import com.eactive.eai.rms.data.entity.man.user.QUserRole;
import com.eactive.eai.rms.data.jpa.AbstractEMSDataSerivce;
import org.hibernate.annotations.QueryHints;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class RoleMenuAuthService extends AbstractEMSDataSerivce<RoleMenuAuth, RoleMenuAuthId, RoleMenuAuthRepository> {

   public String getRoleList(String userId, String menuId, String serviceType) {
		QUserRole qUserRole = QUserRole.userRole;
		QRoleMenuAuth qRoleMenuAuth = QRoleMenuAuth.roleMenuAuth;
		QRole qRole = QRole.role;
		
		return getJPAQueryFactory()
				.select(qRoleMenuAuth.auth.max())
				.from(qUserRole)
				.join(qRole).on(qUserRole.id.roleId.eq(qRole.roleId))
				.join(qRoleMenuAuth).on(qRole.roleId.eq(qRoleMenuAuth.id.roleId))
				.where((qUserRole.id.userId.eq(userId)),
						qRoleMenuAuth.id.menuId.eq(menuId),
						qRoleMenuAuth.auth.in("R", "W"),
                  qRoleMenuAuth.id.serviceType.eq(serviceType),
						qRole.useYn.eq("Y"))
				.setHint(QueryHints.CACHEABLE, true)
				.fetchOne();
	}

   public Iterable<RoleMenuAuth> findAllByRoleId(String roleId) {
      return repository.findAll(QRoleMenuAuth.roleMenuAuth.id.roleId.eq(roleId));
   }

   public List<String> findAllServiceTypeByRoleIds(List<String> roleIds) {

      QRoleMenuAuth qRoleMenuAuth = QRoleMenuAuth.roleMenuAuth;
      QRole qRole = QRole.role;

      return getJPAQueryFactory()
            .select(qRoleMenuAuth.id.serviceType)
            .distinct()
            .from(qRoleMenuAuth)
            .join(qRole).on(qRoleMenuAuth.id.roleId.eq(qRole.roleId))
            .where(qRoleMenuAuth.id.roleId.in(roleIds),
                  qRole.useYn.eq("Y"))
            .setHint(QueryHints.CACHEABLE, true)
            .fetch();
   }

   public List<String> findMenuIdsByServiceType(String serviceType) {

      QRoleMenuAuth qRoleMenuAuth = QRoleMenuAuth.roleMenuAuth;

      return getJPAQueryFactory()
            .select(qRoleMenuAuth.id.menuId)
            .distinct()
            .from(qRoleMenuAuth)
            .where(qRoleMenuAuth.id.serviceType.eq(serviceType))
            .setHint(QueryHints.CACHEABLE, true)
            .fetch();
   }

}
