<?php


namespace Shop\Repositories\Country;


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\Country\CountryCollection;
use Shop\Models\Country\Country;
use Shop\Models\Country\CountryQuery;

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

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

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

        $dbCriteria
            ->_if($criteria->getFilterByCode()!==null)
            ->filterByCode($criteria->getFilterByCode())
            ->_endif()
            ->_if($criteria->getSearchByName()!==null)
            ->filterByName('%'.$criteria->getSearchByName().'%',Criteria::LIKE)
            ->_endif()
        ;
    }

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

        $collection = new CountryCollection();

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

        return $collection;
    }

}