<?php


namespace App\Model\Services;


use App\Model\Entities\Localization\Language;
use App\Model\Entities\Security\User;
use Kdyby\Doctrine\EntityRepository;
use Kdyby\Doctrine\QueryBuilder;

class LanguageService extends BaseService
{
    /** @var  EntityRepository */
    protected $languages;
    
    protected function startup()
    {
        parent::startup();
        
        $this->languages = $this->getRepository(Language::class);
    }


    public function createLanguage(User $createdBy, $identifier, $name) : Language
    {
        $language = new Language($createdBy);
        $language->setIdentifier($identifier);
        $language->setName($name);

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

    /**
     * @return Language[]
     */
    public function getLanguages() : array
    {
        return $this->languages->findAll();
    }

    public function findLanguageById($id)
    {
        return $this->languages->find($id);
    }

    public function findLanguage($identifier)
    {
        $criteria = array('identifier' => $identifier);

        return $this->languages->findOneBy($criteria);
    }

    public function getAvailableLanguagesPairs() : array
    {
        $criteria = array('state' => Language::AVAILABLE);

        return $this->languages->findPairs($criteria, 'name', array('name'), 'identifier');
    }

    /**
     * @return QueryBuilder
     */
    public function getLanguagesGridDataSource() : QueryBuilder
    {
        return $this->languages->createQueryBuilder('language');
    }
}