<?php


namespace Shop\Repositories\Provider;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\Provider\ProviderCollection;
use Shop\Models\Customer\Customer;
use Shop\Models\Provider\Provider;
use Shop\Models\Provider\ProviderQuery;

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

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

    /**
     * @param EntityInterface $entity
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function delete(EntityInterface $entity): void
    {
        /**
         * @var Customer $contractor
         */
        $contractor = $entity->getContractor();
        $contractor->setBlocked('Y');
        $contractor->save();

        parent::delete($entity); // TODO: Change the autogenerated stub
    }

    /**
     * @param PaginationInterface $criteria
     * @param ModelCriteria $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria,$dbCriteria);
        $dbCriteria
            ->_if($criteria->getFilterByName()!==null)
            ->filterByName($criteria->getFilterByName())
            ->_endif()
        ;
    }

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

        $collection = new ProviderCollection();

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

        return $collection;
    }

}