<?php

namespace Diamond\Repositories;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Repository\CrudInterface;
use Core\Repository\PropelQueryAbstract;
use Diamond\Infrastructure\Models\Menu\MenuQuery;
use Propel\Runtime\Collection\ObjectCollection;

/**
 * Работа с хранилищем сущности Menu
 *
 * @author Dmitriy
 */
class Menu extends PropelQueryAbstract implements CrudInterface, RequestAwareInterface
{
    use RequestAwareTrait;

    public function buildEntity(): \Diamond\Infrastructure\Models\Menu\Menu
    {
        return new \Diamond\Infrastructure\Models\Menu\Menu();
    }

    /**
     *
     * @return MenuQuery
     */
    public function buildQueryWithDomain(): MenuQuery
    {
        return MenuQuery::create()
            ->useDomainQuery()
            ->filterByDomain(
                sprintf("'%s' REGEXP `domain`", $this->request->getHost()),
                \Propel\Runtime\ActiveQuery\Criteria::CUSTOM
            )
            ->endUse()
            ;
    }

    public function buildQuery(): MenuQuery
    {
        return MenuQuery::create()
            ;
    }

    /**
     * Поиск меню по имени
     * @param string $name
     * @return ObjectCollection
     */
    public function findByName(string $name): ObjectCollection
    {

        return $this->buildQueryWithDomain()
            ->orderByPosition()
            ->orderById()
            ->filterByName($name)
            ->filterByActive('Y')
            ->find()
            ;
    }

    /**
     *
     * @param type $name
     * @return ObjectCollection
     */
    public function findByNameWithOrderParent($name, bool $onlyActive = true): ObjectCollection
    {
        return $this->buildQueryWithDomain()
            ->orderByParentId()
            ->orderByPosition()
            ->filterByName($name)
            ->_if($onlyActive===true)
            ->filterByActive('Y')
            ->_endif()
            ->find();
    }

}