<?php


namespace App\Model\Facades\Readers;


use App\Model\Exceptions\Db\RecordNotFoundException;
use App\Model\Entities\Localization\Language;
use App\Model\Services\LanguageService;
use Kdyby\Doctrine\QueryBuilder;

class LanguageReader extends BaseReader
{
    /** @var LanguageService */
    protected $languageService;

    public function __construct(LanguageService $languageService)
    {
        $this->languageService = $languageService;
    }

    public function getAvailableLanguagesPairs() : array
    {
        return $this->languageService->getAvailableLanguagesPairs();
    }

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

    /**
     * @param $id
     * @return Language
     * @throws RecordNotFoundException
     */
    public function findLanguageById($id) : Language
    {
        $language = $this->languageService->findLanguageById($id);
        $this->validateEntity($language);

        return $language;
    }

    /**
     * @return Language
     */
    public function getDefaultLanguage() : Language
    {
        return $this->findLanguage('en');
    }

    /**
     * @param $identifier
     * @return Language
     * @throws RecordNotFoundException
     */
    public function findLanguage($identifier) : Language
    {
        $language = $this->languageService->findLanguage($identifier);
        $this->validateEntity($language);

        return $language;
    }

    /**
     * @return QueryBuilder
     */
    public function getGridDataSource() : QueryBuilder
    {
        return $this->languageService->getLanguagesGridDataSource();
    }

    /**
     * @param $language
     * @return Language
     * @throws RecordNotFoundException
     */
    public function validateLanguage($language) : Language
    {
        // is valid entity
        if ($language instanceof Language) {
            return $language;
        }

        // primary key
        if (is_numeric($language)) {
            return $this->findLanguageById($language);
        }

        // language identifier
        return $this->findLanguage($language);
    }
}