<?php
namespace App\Repository;

use App\Entity\ActorEntity;
use App\Entity\TaskEntity;
use App\Enum\StatusEnum;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr\Join;

class TaskRepository extends EntityRepository
{

    /** @var array Default sorting */
    public const DEFAULT_ORDER = [
        'planifiedDate' => 'asc',
        'activity' => 'desc',
        'name' => 'asc',
    ];

    /**
     * {@inheritdoc}
     */
    public function find($id, $lockMode = null, $lockVersion = null): ?TaskEntity
    {
        return parent::find($id, $lockMode, $lockVersion);
    }

    /**
     * {@inheritdoc}
     */
    public function findBy(array $criteria, ?array $orderBy = self::DEFAULT_ORDER, $limit = null, $offset = null)
    {
        return parent::findBy($criteria, $orderBy, $limit, $offset);
    }

    /**
     * {@inheritdoc}
     */
    public function createQueryBuilder($alias, $indexBy = null): QueryBuilder
    {
        $queryBuilder = parent::createQueryBuilder($alias, $indexBy);
        foreach ($this::DEFAULT_ORDER as $field => $order) {
            $queryBuilder->addOrderBy($alias . '.' . $field, $order);
        }

        return $queryBuilder;
    }
    
    public function findActiveFollowed(): array
    {
        // Create criteria
        $criteria = new Criteria();
        $criteria->andWhere($criteria->expr()
            ->eq('actor.followed', true));
        $criteria->andWhere($criteria->expr()
            ->in('task.status', StatusEnum::ACTIVE_STATUS));
        
        $query = $this->createQueryBuilder('task');
        $query->join(ActorEntity::class, 'actor', Join::WITH, 'task.actor = actor');
        $query->addCriteria($criteria);
        
        return $query->getQuery()->execute([], Query::HYDRATE_OBJECT);
    }
}