package inn.ocsf.bee.freigeld.core.service

import inn.ocsf.bee.freigeld.core.model.GlobalWorld
import inn.ocsf.bee.freigeld.core.model.Person
import inn.ocsf.bee.freigeld.core.model.PersonIdentitySecret
import inn.ocsf.bee.freigeld.core.model.PersonMemberPosition
import inn.ocsf.bee.freigeld.core.repo.PersonRepository
import org.springframework.stereotype.Service
import scala.Tuple2
import java.util.*
import javax.inject.Inject

@Service
class WorldService {

    @Inject
    private lateinit var personRepo: PersonRepository

    @Inject
    private lateinit var world: GlobalWorld

    fun findAllByOwnerId(ownerId: UUID): Set<UUID> {
        return personRepo.findAllByOwnerId(ownerId).map { it.person }.map { it.id }.toSet()
    }

    fun findAllByMemberId(memberId: UUID): List<Tuple2<UUID, PersonMemberPosition>> {
        return personRepo.findAllByMemberId(memberId).toList()
    }

    fun findOneByRecoveryCode(code: String, num: Int): Person? {
        return personRepo.findAllBy0().flatMap { p -> p.identities.entries.stream().map { p.id to it.value } }.filter { it.second is PersonIdentitySecret }.map { it.first to (it.second as PersonIdentitySecret) }.filter { it.second.codes?.get(num - 1)?.equals(code) ?: false }.map { personRepo.findById(it.first) }.filter { it.isPresent }.map { it.get() }.map { it.person }.findAny().orElse(null)
    }

}