<?php
namespace App\Repository;

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

/**
 * Repository for workspaces
 */
class ActivityRepository extends EntityRepository
{

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

    /**
     * {@inheritdoc}
     */
    public function findAll(): array
    {
        return $this->findBy([], ActivityRepository::DEFAULT_ORDER);
    }

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

    /**
     * Find active activities of followed actors
     *
     * @return array
     */
    public function findActiveFollowed(): array
    {
        // Create criteria
        $criteria =new Criteria();
        $criteria->andWhere($criteria->expr()
            ->eq('actor.followed', true));
        $criteria->andWhere($criteria->expr()
            ->in('activity.status', StatusEnum::ACTIVE_STATUS));
        
        $query = $this->createQueryBuilder('activity');
        $query->join(ActorEntity::class, 'actor', Join::WITH, 'activity.actor = actor');
        $query->addCriteria($criteria);

        return $query->getQuery()->execute([], Query::HYDRATE_OBJECT);
    }
}