<?php


namespace Shop\Repositories\PriceFile;


use Diamond\Repositories\PropelAbstractRepository;
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\Models\PriceAccess\Map\PriceAccessTableMap;
use Shop\Models\PriceAccess\PriceAccessQuery;
use Shop\Models\PricelistFile\PricelistFile;
use Shop\Models\PricelistFile\PricelistFileQuery;

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

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

    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria,$dbCriteria);
    }

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

        $collection = new PriceFileCollection();

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

        return $collection;
    }

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

}