package gaf3.core.services.bff.service

import gaf3.core.data.PagedData
import gaf3.core.jpa.extension.findAll
import gaf3.core.services.bff.dao.GafBffUserRoleDAO
import gaf3.core.services.bff.entity.BffUserRole
import gaf3.core.services.role.entity.GafRoleItem
import gaf3.core.services.user.domain.UserInfo
import gaf3.core.services.user.entity.GafUserInfo
import gaf3.core.services.user.service.UserService
import org.springframework.data.domain.Example
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service

@Service("gafBffUserRoleService")
class BffUserRoleService(val bffDao: GafBffUserRoleDAO, val userService: UserService) {

    fun find(filter: GafUserInfo, roleId: String?, skip: Int = 0, limit: Int = 100, exact: Boolean = true): PagedData<UserInfo> {
        val example = BffUserRole()
        example.user = filter
        example.target = roleId
        val page:Int = skip/limit
        val paged = bffDao.findAll(example, PageRequest.of(page, limit), exact)
        val rs = paged.content.map { p ->
            if(null == p.user) {
                UserInfo(p.source)
            } else {
                userService.convertDomain(p.user!!, p.acct)
            }
        }

        return PagedData(rs, paged.totalElements.toInt())
    }

    fun find(filter: GafRoleItem, userId: String?, skip: Int = 0, limit: Int = 100): PagedData<GafRoleItem> {
        val temp = BffUserRole()
        temp.role = filter
        temp.source = userId
        val example = Example.of(temp)
        val page:Int = skip/limit
        val paged = bffDao.findAll(example, PageRequest.of(page, limit))
        val rs = paged.content.map { p -> p.role ?: GafRoleItem(p.target) }

        return PagedData(rs, paged.totalElements.toInt())
    }
}