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

namespace App\Modules\Front\Home;

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;
final class HomePresenter extends BaseFrontPresenter
{


    /** @inject @var \App\Model\Database\EntityManager */
    public $em;

    private $translations;
    private $dictionaries;
    private $drsSelect;
    private $slugs;
    public $translation;

    /** @persistent */
    public $term;
    /** @persistent */
    public $slug;

    protected function startup()
    {
	$trs = $this->em->getRepository(Translation::class)->findBy([],['id' => 'ASC','direction'=>'ASC']);
	$drs = $this->em->getRepository(Dictionary::class)->findPairs('id','name');
	$select = [];
	foreach ($trs as $t) {
		$lang1 = $t->getLangName1();
		$lang2 = $t->getLangName2();

		$lang = mb_substr($lang1,0,-1);
		$lang .= "o-".$lang2;
		$slug = Strings::webalize($lang);
		$select[$drs[$t->getDictionary()->getId()]][$t->getId()] = $lang;
		$translations[$t->getId()]["slug"] = $slug;
		$translations[$t->getId()]["lang"] = $lang;
		$translations[$t->getId()]["t"] = $t;
		$slugs[$slug] = $t;

	}
	$this->translations = $translations;
	$this->dictionaries = $drs;
	$this->drsSelect = $select;
	$this->slugs = $slugs;

	parent::startup();
    }

    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"];

	    $query = new $query($t->dictionary,$this->term,$t->direction);
	
	    if ($clen) $query->withClen($clen);
	    $result = $this->repoTerms->fetch($query)->setFetchJoinCollection(FALSE);

	    if ($paginate) {
	            $this["paginator"]->setItemCount($result->getTotalCount());
	            $result->applyPaginator($paginator);
		    $offset = $this['paginator']->getOffset();
	    	    $itemsPerPage = $this['paginator']->getItemsPerPage();
	    }

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

	    return $result;
    }

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

		$paginator->ajax = false;
		$paginator->canSetItemsPerPage = true;
		//$paginator->templateFile = __DIR__ . '/my_awesome_template.latte';

		return $paginator;
	}

    protected function createComponentSearchForm()
    {
	$form = new UI\Form;
	$form->addText('string', 'Výraz')
		->setRequired('Zadajte výray');
	$form->addSelect('translation', 'Preklad', $this->drsSelect)
		->setDefaultValue(1)
		->setRequired('Vyberte slovnik');
	$form->addText('clen','Clen',5);
	$form->addSubmit('search', 'Vyhaľadaj');
	return $form;
    }

    public function searchFormSucceeded(UI\Form $form,$values)
    {
    	    $translation = $values->translation;
	    $clen = $values->clen;
	    $term = $values->string;

	    $result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsQuery',$translation,$term,$clen);

	    $this->template->result = $result;
    }

    public function searchFormSucceededIpa(UI\Form $form,$values)
    {
    	    $translation = $values->translation;
	    $term = $values->string;
	    $clen = $values->clen;

	    $result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsFullQuery',$translation,$term,$clen);

	    $this->template->result = $result;
    }

    public function searchFormSucceededInteractive(UI\Form $form,$values)
    {
	    $term = $values->string;
    	    $translation = $values->translation;

	    $result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsFullQuery',$translation,$term,null);

	    $this->template->result = $result;
    }

    public function actionPlay($id = null)
    {
        $pron = $this->em->getPronunciationRepository()->find(['id'=>$id]);
	    $basepath = $this->getHttpRequest()->url->basePath . "/media";
	    $oggResp = new OggResponse($id,$pron->filename);
	    return $this->sendResponse($oggResp);
	    
    }

    public function beforeRender()
    {
	    $dicttypes = $this->em->getDictTypeRepository()->findAssoc([],'id');
	    $this->template->dicttypes = $dicttypes;
	    $this->template->dictionaries = $this->dictionaries;
	    $this->template->translations = $this->translations;
	 //   $this->template->paginator = $this->paginator;
    }

    public function actionDefault()
    {
	if ($this->getRequest()->isMethod('GET') && $this->term) {
		$this['searchForm']['string']->setValue($this->term);
		$t = $this->slugs[$this->slug];
		$result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsQuery',$t->id,$this->term);
		if ($result) $this->template->result = $result;
	}

	$this['searchForm']->onSuccess[] = array($this, 'searchFormSucceeded');
    }

    public function actionSelect($slug,$term = null)
    {
	$this['searchForm']->onSuccess[] = array($this, 'searchFormSucceededIpa');	
	if ($this->getRequest()->isMethod('GET')) {
		if (isset($this->slugs[$slug])) {
		  $t = $this->slugs[$slug];
		  $this['searchForm']['translation']->setValue($t->id);
		  $translation = $t;
		}  
	} else {
		$id = $this['searchForm']['translation']->value;
		if (isset($this->translations[$id])) {
			$t = $this->translations[$id];
		        $this->redirect('Homepage:select',$t["slug"],$this['searchForm']['string']->value);
		}
	}
	if ($term) {
	    $query = new \App\Model\Database\Repository\TermsFullQuery($translation->dictionary,$term,$translation->direction);
	    $result = $this->repoTerms->fetch($query);

	    $this->template->result = $result;
	    $this->template->translation = $translation;
	}
	$this->setView('ipa');
    }

    public function handleGetInfo($id)
    {
	$term = $this->repoTerms->find($id);
	$termFlags = $this->repoTermFlags->findAssoc([],'id');

  	$dictionary = $term->dictionary;

	$query = new \App\Model\Database\Repository\TermsFullQuery($dictionary,$term->string1,1,false);
	$result = $this->repoTerms->fetch($query);

	$this->template->result = $result;
	$this->template->termFlags = $termFlags;

	$this->setView('info');
    }

    public function renderDefault()
    {
    }

    public function actionIpa()
    {
	if ($this->getRequest()->isMethod('GET')) {
	   if ($this->term) {
		$this['searchForm']['string']->setValue($this->term);
		$result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsFullQuery',$this->slugs[$this->slug]->id,$this->term);
		if ($result) $this->template->result = $result;
	    }
	}

	$this['searchForm']->onSuccess[] = array($this, 'searchFormSucceededIpa');
    }

    public function actionInteractive()
    {
	if ($this->getRequest()->isMethod('GET')) {
	   if ($this->term) {
		$this['searchForm']['string']->setValue($this->term);
		$result = $this->doSearch('\\App\\Model\\Database\\Repository\\TermsFullQuery',$this->slugs[$this->slug]->id,$this->term);
		if ($result) $this->template->result = $result;
	    }
	}

	$this['searchForm']->onSuccess[] = array($this, 'searchFormSucceededInteractive');
    }

    public function renderAutocomplete($whichData, $typedText = '',$translation = 1)
    {
	    $translation = $this->repoTranslations->find($translation);

	    $query = new \App\Model\Database\Repository\TermsQuickQuery($translation->dictionary,$typedText,$translation->direction);
	    $result = $this->repoTerms->fetch($query);

	    $map = [];
	    foreach ($result as $str) {
		$map[] = $str["string1"];
	    }

	    return $this->sendResponse(new JsonResponse($map));
    }

    public function renderIpa()
    {

    }

    public function renderMerge()
    {

    }
}


