<?php


namespace Shop\Repositories\Region;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\Region\Contracts\RegionCriteriaInterface;
use Shop\Domain\Region\RegionCollection;
use Shop\Models\Region\Region;
use Shop\Models\Region\RegionQuery;

class RegionRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
    public static function createEntity(): EntityInterface
    {
        return new Region();
    }

    protected function createQuery(): ModelCriteria
    {
        return RegionQuery::create();
    }

    /**
     * @param PaginationInterface|RegionCriteriaInterface $criteria
     * @param ModelCriteria|RegionQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria, $dbCriteria);

        $dbCriteria
            ->_if($criteria->getSearchByName() !== null)
            ->filterByName('%' . $criteria->getSearchByName() . '%', Criteria::LIKE)
            ->_endif()
            ->_if($criteria->getFilterByCountryId() !== null)
            ->filterByCountryId($criteria->getFilterByCountryId())
            ->_endif()
            ->_if($criteria->getSortByName() !== null)
            ->orderByName($criteria->getSortByName())
            ->_endif();
    }

    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        $this->modifyCriteria($criteria, $query);
        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = new RegionCollection();

        foreach ($result->getResults() as $row) {
            $collection->push($row);
        }

        return $collection;
    }

}