<?php


namespace Shop\Infrastructure\Repositories\PriceFile;


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\PriceFile\PriceFileCollection;
use Shop\Infrastructure\Models\PriceAccess\Map\PriceAccessTableMap;
use Shop\Infrastructure\Models\PriceAccess\PriceAccessQuery;
use Shop\Infrastructure\Models\PricelistFile\PricelistFile;
use Shop\Infrastructure\Models\PricelistFile\PricelistFileQuery;

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

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

    /**
     * @param PaginationInterface|PriceFileCriteria $criteria
     * @param ModelCriteria|PricelistFileQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $dbCriteria
            ->_if($criteria->getSortByName() !== null)
            ->orderByName($criteria->getSortByName())
            ->_endif()
            ->_if($criteria->getSearchByName() !== null)
            ->filterByName('%' . $criteria->getSearchByName() . '%', Criteria::LIKE)
            ->_endif()
            ;
    }
    

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

    /**
     * @param EntityInterface|PricelistFile $entity
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function delete(EntityInterface $entity): void
    {
        $con = Propel::getServiceContainer()->getWriteConnection(PriceAccessTableMap::DATABASE_NAME);
        $con->beginTransaction();
        $price = $entity->getPricelistSheets()->getFirst();
        if ($price) {
            PriceAccessQuery::create()->filterByPriceScheetId($price->getId())->delete();
        }
        parent::delete($entity); // TODO: Change the autogenerated stub
        $con->commit();
    }

}