<?php


namespace Shop\Repositories\PricePosition;


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\PricePosition\Contracts\PricePositionCriteriaInterface;
use Shop\Domain\PricePosition\PricePositionCollection;
use Shop\Models\Position\Position;
use Shop\Models\Position\PositionQuery;

class PricePositionRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{
    /**
     * @return EntityInterface
     */
    public static function createEntity(): EntityInterface
    {
        return new Position();
    }

    /**
     * @return ModelCriteria
     * @throws \Propel\Runtime\Exception\PropelException
     */
    protected function createQuery(): ModelCriteria

    {
        return PositionQuery::create()->withComplexRate();
    }

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

        $dbCriteria
            ->_if($criteria->getFilterByProductId() !== null)
            ->filterByProductId($criteria->getFilterByProductId())
            ->_endif()
            ->_if($criteria->getFilterByRefId() !== null)
            ->filterByRefId($criteria->getFilterByRefId())
            ->_endif()
            ->_if($criteria->getFilterByPricelistSheetId() !== null)
            ->filterByPricelistSheetId($criteria->getFilterByPricelistSheetId())
            ->_endif()
            ->_if($criteria->getSearchByProductName() !== null)
            ->useProductQuery()
            ->filterByTitle('%' . $criteria->getSearchByProductName() . '%', Criteria::LIKE)
            ->endUse()
            ->_endif();
    }

    /**
     * @param PaginationInterface $criteria
     * @return CollectionInterface
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {
        $query = $this->createQuery();
        $this->modifyCriteria($criteria, $query);
        $result = $query->paginate($criteria->getPage(), $criteria->getLimit());

        $collection = new PricePositionCollection();

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

        return $collection;
    }

}