<?php

namespace Comitium5\DesignerBundle\Repository\Template;


use Comitium5\DesignerBundle\Repository\AbstractRepository;
use Comitium5\DesignerBundle\Model\Interfaces\SearchableRepositoryInterface;


/**
 * Class TemplateRepository
 *
 * @author Oscar Jimenez <oscarjg19.developer@gmail.com>
 * @package Comitium5\DesignerBundle\Repository\Template
 */
class TemplateRepository extends AbstractRepository implements SearchableRepositoryInterface
{
    /**
     * @param $term
     * @param array $params
     *
     * @return mixed
     */
    public function search($term, array $params = array())
    {
        $builder = $this->createQueryBuilder("t");

        foreach (explode(' ', $term) as $key => $word) {
            $builder
                ->andWhere("CONCAT_WS('', t.name, t.description) LIKE ?$key")
                ->setParameter("$key", "%$word%");
        }

        return $builder;
    }

    /**
     * @param $layoutId
     * @return mixed
     */
    public function findByLayout($layoutId)
    {
        $builder = $this->createQueryBuilder("t");

        $builder->innerJoin('t.layouts', 'tl');
		$builder->andWhere('tl.id = :layout');
		$builder->setParameter('layout', $layoutId);

        return $builder;
    }

    /**
     * @return \Doctrine\ORM\QueryBuilder
     */
    public function queryInitialList()
    {
        return $this
                ->createQueryBuilder("t")
                ->where("t.group = :group")
                ->andWhere("t.parent = :parent")
                ->setParameter("group", null)
                ->setParameter("parent", null)
            ;
    }

    /**
     * @return array|\Doctrine\ORM\QueryBuilder|int|string
     */
    public function findByInitialList()
    {
        return $this->queryInitialList()->getQuery()->getResult();
    }
}
