<?php


namespace App\Model\Facades\Readers;


use App\Model\Entities\Game;
use App\Model\Entities\GameData\GameData;
use App\Model\Services\GameService;
use Kdyby\Doctrine\QueryBuilder;

class GameReader extends BaseReader
{
    /** @var GameService */
    protected $gameService;

    public function __construct(GameService $gameService)
    {
        $this->gameService = $gameService;
    }

    /**
     * @param int $id
     * @return Game
     */
    public function findGameById(int $id) : Game
    {
        $game = $this->gameService->findGameById($id);
        $this->validateEntity($game);

        return $game;
    }

    /**
     * @return GameData[]
     */
    public function getGames() : array
    {
        return $this->gameService->getGames();
    }

    public function getAdminGridDataSource() : QueryBuilder
    {
        return $this->gameService->getGameGridDataSource();
    }

    public function getGridDataSource() : QueryBuilder
    {
        return $this->gameService->getGameGridDataSource()->where('g.state = :state')->setParameter('state', Game::ACTIVE);
    }

    public function validateGame($game) : Game
    {
        // is valid entity
        if ($game instanceof Game) {
            return $game;
        }

        // try primary key
        return $this->findGameById($game);
    }

}