<?php namespace RVR\Repository;

use Generator;
use RVR\PersistentData\Model\Community;
use RVR\PersistentData\Model\CommunityMember;
use RVR\PersistentData\Model\User;
use SokoWeb\Database\Query\Select;

class CommunityMemberRepository
{
    public function getById(int $id): ?CommunityMember
    {
        return \Container::$persistentDataManager->selectFromDbById($id, CommunityMember::class);
    }

    public function getAllByCommunity(Community $community, bool $useRelations = false, array $withRelations = []): Generator
    {
        $select = new Select(\Container::$dbConnection);
        $select->where('community_id', '=', $community->getId());

        yield from \Container::$persistentDataManager->selectMultipleFromDb($select, CommunityMember::class, $useRelations, $withRelations);
    }

    public function getAllByUser(User $user, bool $useRelations = false, array $withRelations = []): Generator
    {
        $select = new Select(\Container::$dbConnection);
        $select->where('user_id', '=', $user->getId());

        yield from \Container::$persistentDataManager->selectMultipleFromDb($select, CommunityMember::class, $useRelations, $withRelations);
    }

    public function getByCommunityAndUser(Community $community, User $user) : ?CommunityMember
    {
        $select = new Select(\Container::$dbConnection);
        $select->where('community_id', '=', $community->getId());
        $select->where('user_id', '=', $user->getId());

        return \Container::$persistentDataManager->selectFromDb($select, CommunityMember::class);
    }
}