<?php


namespace Shop\Repositories\City;


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\City\CityCollection;
use Shop\Domain\City\Contracts\CityCriteriaInterface;
use Shop\Models\City\City;
use Shop\Models\City\CityQuery;

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

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

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

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

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

        $collection = new CityCollection();

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

        return $collection;
    }

}