<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\ActivityBundle\Export\Aggregator\ACPAggregators;

use Chill\ActivityBundle\Entity\Activity;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;

class ByActivityNumberAggregator implements AggregatorInterface
{
    public function addRole(): ?string
    {
        return null;
    }

    public function alterQuery(QueryBuilder $qb, $data, \Chill\MainBundle\Export\ExportGenerationContext $exportGenerationContext): void
    {
        $qb
            // Use a distinct alias inside the subquery to avoid colliding with the root alias "activity"
            ->addSelect('(SELECT COUNT(agg_activity.id) FROM '.Activity::class.' agg_activity WHERE agg_activity.accompanyingPeriod = acp) AS activity_by_number_aggregator')
            ->addGroupBy('activity_by_number_aggregator');
    }

    public function applyOn(): string
    {
        return Declarations::ACP_TYPE;
    }

    public function buildForm(FormBuilderInterface $builder): void
    {
        // No form needed
    }

    public function getNormalizationVersion(): int
    {
        return 1;
    }

    public function normalizeFormData(array $formData): array
    {
        return [];
    }

    public function denormalizeFormData(array $formData, int $fromVersion): array
    {
        return [];
    }

    public function getFormDefaultData(): array
    {
        return [];
    }

    public function getLabels($key, array $values, $data): callable
    {
        return static function ($value) {
            if ('_header' === $value) {
                return 'Count activities linked to an accompanying period';
            }

            if (null === $value) {
                return '';
            }

            return $value;
        };
    }

    public function getQueryKeys($data): array
    {
        return ['activity_by_number_aggregator'];
    }

    public function getTitle(): string
    {
        return 'Group acp by activity number';
    }
}
