<?php

namespace App\Model\Services;

use App\Model\Entities\Game;
use App\Model\Entities\GameData\GameData;
use App\Model\Entities\GameData\Mmorpg\MmorpgData;
use App\Model\Entities\GameData\Publisher;
use App\Model\Entities\GameData\Studio;
use App\Model\Entities\Security\User;
use App\Model\Interfaces\IGameData;
use Kdyby\Doctrine\Dql\Join;
use Kdyby\Doctrine\EntityRepository;
use Kdyby\Doctrine\QueryBuilder;

class GameService extends BaseService
{
    /** @var EntityRepository */
    protected $games;

    protected function startup()
    {
        parent::startup();

        $this->games = $this->getRepository(Game::class);
    }

    public function createGame(User $createdBy, $name, IGameData $gameData)
    {
        $game = new Game($createdBy, $gameData);
        $game->setName($name);

        $this->persist($game);
        return $game;
    }

    public function createMmoGameData(Publisher $publisher, Studio $studio, $version,
                                      int $maxLevel = 0, int $craftingProfLimit = 0, int $primaryProfLimit = 0,
                                      int $secondaryProfLimit = 0) : MmorpgData
    {
        $gameData = new MmorpgData();
        $gameData->setPublisher($publisher);
        $gameData->setStudio($studio);
        $gameData->setVersion($version);

        $gameData->setMaximumLevel($maxLevel);
        $gameData->setCraftingProfessionsLimit($craftingProfLimit);
        $gameData->setPrimaryProfessionsLimit($primaryProfLimit);
        $gameData->setSecondaryProfessionsLimit($secondaryProfLimit);

        $this->persist($gameData);
        return $gameData;
    }

    /**
     * @param $id
     * @return null|Game
     */
    public function findGameById(int $id)
    {
        return $this->games->find($id);
    }

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

    /**
     * @return QueryBuilder
     */
    public function getGameGridDataSource() : QueryBuilder
    {
        return $this->games->createQueryBuilder('g')
            ->leftJoin(GameData::class, 'd', Join::WITH, "d.id = g.gameData")
            ->leftJoin(Publisher::class, "p", Join::WITH, "p.id = d.publisher")
            ->leftJoin(Studio::class, "s", Join::WITH, "s.id = d.studio");
    }

    public function getUsersGames($user)
    {
        // todo: implement manyToMany filter
    }
}