<?php


namespace App\Model\Services;


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

class RegionService extends BaseService
{
    /** @var  EntityRepository */
    protected $regions;

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

        $this->regions = $this->getRepository(Region::class);
    }

    public function createRegion(User $createdBy, Game $game, string $name, $identifier = null) : Region
    {
        $region = new Region($createdBy);
        $region->setName($name);
        $region->setApiIdentifier($identifier);
        $region->setGame($game);

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

    /**
     * @param int $id
     * @return null|Region
     */
    public function findRegionById(int $id)
    {
        return $this->regions->find($id);
    }

    /**
     * @param Game $game
     * @return Region[]
     */
    public function getRegions(Game $game) : array
    {
        return $this->regions->findBy(['game' => $game]);
    }

    /**
     * @param Game $game
     * @return array
     */
    public function getRegionsIdentifiers(Game $game) : array
    {
        return $this->regions->findPairs(['game' => $game], 'apiIdentifier');
    }

    /**
     * @param Game $game
     * @return QueryBuilder
     */
    public function getRegionsGridDataSource(Game $game) : QueryBuilder
    {
        return $this->regions->createQueryBuilder('region')->where('region.game = :game')->setParameter('game', $game);
    }

    public function getSelectBoxData($gameEntity, $all) : array
    {
        $criteria = ['game' => $gameEntity];
        if (!$all) {
            $criteria['state'] = Region::ACTIVE;
        }

        return $this->regions->findPairs($criteria, 'name', ['name' => 'ASC']);
    }

}