<?php


namespace Shop\Repositories\PriceList;


use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\Propel;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\PriceList\PriceListCollection;
use Shop\Models\PriceAccess\Map\PriceAccessTableMap;
use Shop\Models\PriceAccess\PriceAccessQuery;
use Shop\Models\PricelistSheet\PricelistSheet;
use Shop\Models\PricelistSheet\PricelistSheetQuery;

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

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

    /**
     * @param PaginationInterface|PriceListCriteria $criteria
     * @param ModelCriteria|PricelistSheetQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {

        $this->modifyCriteriaForFilterSort($criteria, $dbCriteria);
        $dbCriteria
            //----------
            ->_if($criteria->getSortByTitle()!==null)
            ->orderByTitle($criteria->getSortByTitle())
            ->_endif()

            ->_if($criteria->getFilterByProviderId() !== null)
            ->usePricelistFileQuery()
            ->filterByProviderId($criteria->getFilterByProviderId())
            ->endUse()
            ->_endif()
            //----------
            ->_if($criteria->getSearchByTitle() !== null)
            ->filterByTitle('%' . $criteria->getSearchByTitle() . '%', Criteria::LIKE)
            ->_endif()
            //----------
            ->_if($criteria->getSortByDateUpdate() !== null)
            ->orderByDateUpdate($criteria->getSortByDateUpdate())
            ->_endif();
    }

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

        $collection = new PriceListCollection();

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

        return $collection;
    }

    public function delete(EntityInterface $entity): void
    {
        $con = Propel::getServiceContainer()->getWriteConnection(PriceAccessTableMap::DATABASE_NAME);
        $con->beginTransaction();
        PriceAccessQuery::create()->filterByPriceScheetId($entity->getId())->delete();
        parent::delete($entity); // TODO: Change the autogenerated stub
        $con->commit();
    }


}