<?php declare(strict_types = 1);

namespace App\Model\Database\Repository;

use Doctrine\ORM\EntityRepository;
use App\Model\Database\Entity\Dictionary;

class TermsQuery extends EntityRepository
{

	private Dictionary $dictionary;
	private String $string;
	private Int $direction;
	private String $clen;

	public function __construct(Dictionary $dict,String $string,Int $direction = 1)
	{
		$this->dictionary = $dict;
		$this->string = $string;
		$this->direction = $direction;		
	}

	public function withClen(String $clen)
	{
		if ($clen != null && $clen != '')
			$this->clen = $clen;
	}

	/**
	 * Fetches all records like $key => $value pairs
	 *
	 * @param mixed[] $criteria
	 * @param mixed[] $orderBy
	 * @return mixed[]
	 */
	protected function doCreateQuery()
	{
		$query = $this->createQueryBuilder('t')->select('t')
		    ->addSelect('s1')
		    ->addSelect('s2')
		    ->leftJoin('t.suffix1','s1')
		    ->leftJoin('t.suffix2','s2');
		if ($this->direction == 1) {
		    $query->where('t.string1 LIKE :str')->setParameter('str',$this->string."%");
		    $query->orderBy('t.string1,t.id','ASC');
		} else	if ($this->direction == 2) {
		    $query->where('t.string2 LIKE :str')->setParameter('str', $this->string."%");
		    $query->orderBy('t.string2','ASC');
		    $query->addOrderBy('t.order2','ASC');
		}
		$query->andWhere('t.dictionary = :dict')->setParameter(':dict',$this->dictionary->id);
		if ($this->clen) 
		   $query->andWhere('t.member LIKE :clen')->setParameter('clen','%'.$this->clen.'%');

		return $query;
	}	
}
