package inn.ocsf.bee.freigeld.core.repo

import inn.ocsf.bee.freigeld.core.model.PersonMemberPosition
import inn.ocsf.bee.freigeld.core.model.PrivatePerson
import inn.ocsf.bee.freigeld.core.model.data.PersonDataPrj0p
import org.bson.types.ObjectId
import org.springframework.data.mongodb.core.MongoOperations
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import scala.Tuple2
import java.util.*
import javax.inject.Inject
import kotlin.collections.HashMap

class PersonRepositoryImpl : PersonRepositoryCustom {

    @Inject
    private lateinit var mongo: MongoOperations

    override fun findAllByOwnerId(ownerId: UUID): Collection<PersonDataPrj0p> {
        return mongo.find(Query.query(Criteria.where("_id.ownerId").`is`(ownerId)), HashMap::class.java, "person-owner-view").map {
            val id = (it.get("_id") as Map<String, Any>?) ?: mapOf()
            val ret = object : PersonDataPrj0p {

                override fun getId(): ObjectId {
                    return id.get("_id") as ObjectId
                }

                override fun getPerson(): PrivatePerson {
                    val fake = object : PrivatePerson {
                        override fun getOwnerId(): UUID {
                            return id.get("ownerId") as UUID
                        }

                        override fun getId(): UUID {
                            return id.get("personId") as UUID
                        }
                    }
                    return fake
                }
            }
            ret
        }.toMutableList()
    }

    override fun findAllByMemberId(memberId: UUID): Collection<Tuple2<UUID, PersonMemberPosition>> {
        return mongo.find(Query.query(Criteria.where("_id.memberId").`is`(memberId)), HashMap::class.java, "person-member-view").map {
            val id = (it.get("_id") as Map<String, Any>?) ?: mapOf()
            val position = PersonMemberPosition.valueOf(id.get("position") as String)
            val personId = id.get("personId") as UUID
            Tuple2(personId, position)
        }
    }
}