<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 26.08.2020
 * Time: 14:55
 */

namespace Diamond\Repositories\Site;

use Diamond\Domain\Site\Contracts\SiteCriteriaInterface;
use Diamond\Domain\Site\SiteCollection;
use Diamond\Infrastructure\Models\Domain\Doamin;
use Diamond\Infrastructure\Models\Domain\Domain;
use Diamond\Infrastructure\Models\Domain\DomainQuery;
use Diamond\Repositories\PropelAbstractRepository;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Repo\CollectionInterface;
use Repo\CrudRepositoryBuilderInterface;
use Repo\EntityInterface;
use Repo\PaginationInterface;

class SiteRepository extends PropelAbstractRepository implements CrudRepositoryBuilderInterface
{

    public static function createEntity(): EntityInterface
    {
        return new Domain();
    }

    protected function createCollection(): CollectionInterface
    {
        return new SiteCollection();
    }
    
    /**
     * @param PaginationInterface|SiteCriteriaInterface $criteria
     * @param ModelCriteria|DomainQuery $dbCriteria
     */
    protected function modifyCriteria(PaginationInterface $criteria, ModelCriteria $dbCriteria): void
    {
        $dbCriteria
            ->_if($criteria->getSearchByName()!==null)
            ->filterByName('%' . $criteria->getSearchByName() . '%',Criteria::LIKE)
            ->_endif()
            ->_if($criteria->getSearchByHost()!==null)
            ->withColumn(sprintf("LOCATE(domain,'%s')",$criteria->getSearchByHost()),'priority')
            ->filterByDomain(
                sprintf("LOCATE(domain,'%s') IN (0,1) AND '%s' REGEXP `domain`",
                    $criteria->getSearchByHost(),
                    $criteria->getSearchByHost()
                ), Criteria::CUSTOM)
            ->orderBy('priority',Criteria::DESC)
            ->_endif()
            ->_if($criteria->getSortByHost() !== null)
            ->orderByDomain($criteria->getSortByHost())
            ->_endif()
            ;

    }

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


}