<?php //declare(strict_types = 1);

namespace App\Modules\Front\Search;

use App\Modules\Front\BaseFrontPresenter;
use Nette;
use Nette\Utils\Strings;
use Nette\Application\UI;
use Dict\OggResponse;
use Nette\Application\Responses\JsonResponse;
use AlesWita\VisualPaginator\VisualPaginator;
use AlesWita\VisualPaginator\VisualPaginatorFactory;
use App\Model\Database\EntityManager;
use App\Model\Database\Entity\Dictionary;
use App\Model\Database\Entity\Translation;
use App\Model\Database\Repository\TranslationRepository;
use App\Model\Database\Repository\TermsFullQuery;
use App\Model\Database\Repository\TermsQuickQuery;
use App\Model\Database\Facade\TermFacade;

class SearchPresenter extends BaseFrontPresenter
{


	protected function doSearch($query, $translation, $term, $clen = null, $paginate = true)
	{
		$t = $this->em->getTranslationRepository()->find($translation);

		if ($term) $this->term = $term;
		if ($translation) $this->translation = $translation;
		$this->slug = $this->translations[$translation]["slug"];

		$this->termFacade->setDirection(1);
		$q = $this->termFacade->findByString($term, $t->dictionary, $clen);
		
		if ($paginate) {
			$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($q);
			$count = count($paginator);
			$this["paginator"]->setItemCount($count);
			$offset = $this["paginator"]->getOffset();
			$itemsPerPage = $this['paginator']->getItemsPerPage();
			$q->setFirstResult($offset)->setMaxResults($itemsPerPage);
		}


		$this->template->translation = $t;

		return $q->getResult();
	}

    public function renderDefault($translation,$term,$clen = '',$paginate = true) 
    {
		$this['searchForm']['string']->setValue($this->term);
        $this->template->result = $this->doSearch('TermQuery',$translation,$term,$clen,$paginate);
    }

	public function renderIpa($translation,$term,$clen='',$paginate=true)
	{
		$this['searchForm']['string']->setValue($this->term);
		$result = $this->doSearch('TermsFullQuery', $this->slugs[$this->slug]->id, $this->term);
		if ($result) $this->template->result = $result;
		
		$this['searchForm']->onSuccess[] = array($this, 'searchFormSucceededIpa');
	}
	

	/**
	 * @return AlesWita\Components\VisualPaginator
	 */
	protected function createComponentPaginator(): VisualPaginator
	{
		$paginator = $this->visualPaginatorFactory->create();

		$paginator->ajax = false;
		$paginator->canSetItemsPerPage = true;
		$paginator->setItemsPerPage(20);

		$paginator->templateFile = __DIR__.'/templates/bootstrap4.latte';

		return $paginator;
	}

}

?>