<?php

namespace Shop\Repositories\ImageDefault;

use Diamond\Repositories\PropelAbstractRepository;
use Shop\Domain\ImageDefault\Contracts\ImageDefaultCriteriaInterface;
use Shop\Domain\ImageDefault\Contracts\ImageDefaultEntityInterface;
use Shop\Domain\ImageDefault\ImageDefaultCollection;
use Shop\Models\ImageDefault\ImageDefault;
use Shop\Models\ImageDefault\ImageDefaultQuery;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;
use Shop\Domain\Brand\Contracts\BrandEntityInterface;
use Shop\Domain\ProductCategory\Contracts\ProductCategoryEntityInterface;

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

    /**
     * @return ModelCriteria|ImageDefaultQuery
     */
    protected function createQuery(): ModelCriteria
    {
        return ImageDefaultQuery::create();
    }

    /**
     * @param PaginationInterface|ImageDefaultCriteriaInterface $criteria
     * @param ModelCriteria|ImageDefaultQuery $dbCriteria
     *
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $this->modifyCriteriaForFilterSort($criteria, $dbCriteria);
        $dbCriteria
            ->_if($criteria->getFilterByCategoryId() !== null)
            ->filterByCategoryId($criteria->getFilterByCategoryId())
            ->_endif()
            ->_if($criteria->getFilterByBrandId() !== null)
            ->filterByBrandId($criteria->getFilterByBrandId())
            ->_endif();

    }

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

        $collection = new ImageDefaultCollection();

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

        return $collection;
    }


    /**
     * @param $category
     * @param $brand
     * @return ImageDefaultEntityInterface|null
     */
    public function findByCategoryIdOrBrandId(?ProductCategoryEntityInterface $category,
                                              ?BrandEntityInterface
                                              $brand): ?ImageDefaultEntityInterface
    {

        return $this->createQuery()
            ->_if($category !== null)
            ->filterByCategoryId($category->getId())
            ->_or()
            ->filterByCategoryId(null)
            ->_endif()
            ->_if($brand !== null)
            ->filterByBrandId($brand->getId())
            ->_or()
            ->filterByBrandId(null)
            ->_endif()
            ->findOne();
    }


}