<?php namespace MapGuesser\Repository;

use SokoWeb\Database\Query\Select;
use MapGuesser\PersistentData\Model\Challenge;
use MapGuesser\PersistentData\Model\Map;
use MapGuesser\PersistentData\Model\Place;

class MapRepository
{
    public function getById(int $mapId): ?Map
    {
        return \Container::$persistentDataManager->selectFromDbById($mapId, Map::class);
    }

    public function getByPlace(Place $place): ?Map
    {
        return $this->getById($place->getMapId());
    }

    public function getByChallenge(Challenge $challenge): ?Map
    {
        $select = new Select(\Container::$dbConnection);
        $select->innerJoin('places', ['maps', 'id'], '=', ['places', 'map_id']);
        $select->innerJoin('place_in_challenge', ['places', 'id'], '=', ['place_in_challenge', 'place_id']);
        $select->where(['place_in_challenge', 'challenge_id'], '=', $challenge->getId());
        $select->limit(1);

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