<?php


namespace App\Model\Services;


use App\Model\Entities\Game;
use App\Model\Entities\GameData\Mmorpg\Region;
use App\Model\Entities\GameData\Mmorpg\Server;
use App\Model\Entities\Security\User;
use Kdyby\Doctrine\Dql\Join;
use Kdyby\Doctrine\EntityRepository;
use Kdyby\Doctrine\QueryBuilder;

class ServerService extends BaseService
{
    /** @var  EntityRepository */
    protected $servers;

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

        $this->servers = $this->getRepository(Server::class);
    }

    public function findServerById(int $id)
    {
        return $this->servers->find($id);
    }

    /**
     * @param User $createdBy
     * @param Region $region
     * @param $name
     * @return Server
     */
    public function createServer(User $createdBy, Region $region, string $name) : Server
    {
        $server = new Server($createdBy);
        $server->setName($name);
        $server->setRegion($region);

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

    /**
     * @param Game $game
     * @return QueryBuilder
     */
    public function getServersGridDataSource(Game $game) : QueryBuilder
    {
        return $this->servers->createQueryBuilder('s')
            ->leftJoin(Region::class, "region", Join::WITH, "region.id = s.region")
            ->where('region.game = :game')->setParameter('game', $game);
    }

    public function getSelectBoxPairs(Region $region) : array
    {
        return $this->servers->findPairs(['region' => $region], 'name', ['name' => 'ASC']);
    }

}