<?php


namespace Shop\Infrastructure\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\Infrastructure\Models\PriceAccess\Map\PriceAccessTableMap;
use Shop\Infrastructure\Models\PriceAccess\PriceAccessQuery;
use Shop\Infrastructure\Models\PricelistSheet\PricelistSheet;
use Shop\Infrastructure\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
    {
        
        $dbCriteria
            //----------
            ->_if($criteria->getSortByTitle()!==null)
            ->orderByTitle($criteria->getSortByTitle())
            ->_endif()

            ->_if($criteria->getFilterByPricelistFileId() !== null)
            ->filterByPricelistFileId($criteria->getFilterByPricelistFileId())
            ->_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();
    }


    protected function createCollection(): CollectionInterface
    {
        return new PriceListCollection();
    }

    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();
    }


}