<?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\AsideActivityBundle\Export\Export;

use Chill\AsideActivityBundle\Entity\AsideActivity;
use Chill\AsideActivityBundle\Export\Declarations;
use Chill\AsideActivityBundle\Repository\AsideActivityCategoryRepository;
use Chill\AsideActivityBundle\Security\AsideActivityVoter;
use Chill\AsideActivityBundle\Templating\Entity\CategoryRender;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Export\FormatterInterface;
use Chill\MainBundle\Export\GroupedExportInterface;
use Chill\MainBundle\Export\Helper\DateTimeHelper;
use Chill\MainBundle\Export\Helper\UserHelper;
use Chill\MainBundle\Export\ListInterface;
use Chill\MainBundle\Repository\CenterRepositoryInterface;
use Chill\MainBundle\Repository\LocationRepository;
use Chill\MainBundle\Repository\ScopeRepositoryInterface;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\FormBuilderInterface;

final readonly class ListAsideActivity implements ListInterface, GroupedExportInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private DateTimeHelper $dateTimeHelper,
        private UserHelper $userHelper,
        private ScopeRepositoryInterface $scopeRepository,
        private CenterRepositoryInterface $centerRepository,
        private AsideActivityCategoryRepository $asideActivityCategoryRepository,
        private CategoryRender $categoryRender,
        private LocationRepository $locationRepository,
        private TranslatableStringHelperInterface $translatableStringHelper,
    ) {}

    public function buildForm(FormBuilderInterface $builder) {}

    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 getAllowedFormattersTypes()
    {
        return [FormatterInterface::TYPE_LIST];
    }

    public function getDescription()
    {
        return 'export.aside_activity.List of aside activities';
    }

    public function getGroup(): string
    {
        return 'export.Exports of aside activities';
    }

    public function getLabels($key, array $values, $data)
    {
        return match ($key) {
            'id', 'note' => static function ($value) use ($key) {
                if ('_header' === $value) {
                    return 'export.aside_activity.'.$key;
                }

                return $value ?? '';
            },
            'duration' => static function ($value) use ($key) {
                if ('_header' === $value) {
                    return 'export.aside_activity.'.$key;
                }

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

                if ($value instanceof \DateTimeInterface) {
                    return $value->format('H:i:s');
                }

                return $value;
            },
            'createdAt', 'updatedAt', 'date' => $this->dateTimeHelper->getLabel('export.aside_activity.'.$key),
            'agent_id', 'creator_id' => $this->userHelper->getLabel($key, $values, 'export.aside_activity.'.$key),
            'aside_activity_type' => function ($value) {
                if ('_header' === $value) {
                    return 'export.aside_activity.aside_activity_type';
                }

                if (null === $value || '' === $value || null === $c = $this->asideActivityCategoryRepository->find($value)) {
                    return '';
                }

                return $this->categoryRender->renderString($c, []);
            },
            'location' => function ($value) {
                if ('_header' === $value) {
                    return 'export.aside_activity.location';
                }

                if (null === $value || '' === $value || null === $l = $this->locationRepository->find($value)) {
                    return '';
                }

                return $l->getName();
            },
            'main_scope' => function ($value) {
                if ('_header' === $value) {
                    return 'export.aside_activity.main_scope';
                }

                if (null === $value || '' === $value || null === $c = $this->scopeRepository->find($value)) {
                    return '';
                }

                return $this->translatableStringHelper->localize($c->getName());
            },
            'main_center' => function ($value) {
                if ('_header' === $value) {
                    return 'export.aside_activity.main_center';
                }

                if (null === $value || '' === $value || null === $c = $this->centerRepository->find($value)) {
                    /* @var Center $c */
                    return '';
                }

                return $c->getName();
            },
            default => throw new \LogicException('this key is not supported : '.$key),
        };
    }

    public function getQueryKeys($data): array
    {
        return [
            'id',
            'createdAt',
            'updatedAt',
            'agent_id',
            'creator_id',
            'main_scope',
            'main_center',
            'aside_activity_type',
            'date',
            'duration',
            'note',
            'location',
        ];
    }

    public function getResult($query, $data, \Chill\MainBundle\Export\ExportGenerationContext $context): array
    {
        return $query->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
    }

    public function getTitle(): string|\Symfony\Contracts\Translation\TranslatableInterface
    {
        return 'export.aside_activity.List of aside activities';
    }

    public function getType(): string
    {
        return Declarations::ASIDE_ACTIVITY_TYPE;
    }

    public function initiateQuery(array $requiredModifiers, array $acl, array $data, \Chill\MainBundle\Export\ExportGenerationContext $context): \Doctrine\ORM\QueryBuilder
    {
        $qb = $this->em->createQueryBuilder()
            ->from(AsideActivity::class, 'aside')
            ->leftJoin('aside.agent', 'agent')
            ->leftJoin('agent.scopeHistories', 'scopeHistories')
            ->andWhere('scopeHistories.startDate <= aside.date AND (scopeHistories.endDate IS NULL or scopeHistories.endDate > aside.date)')
        ;

        $qb
            ->addSelect('aside.id AS id')
            ->addSelect('aside.createdAt AS createdAt')
            ->addSelect('aside.updatedAt AS updatedAt')
            ->addSelect('IDENTITY(aside.agent) AS agent_id')
            ->addSelect('IDENTITY(aside.createdBy) AS creator_id')
            ->addSelect('IDENTITY(scopeHistories.scope) AS main_scope')
            ->addSelect('IDENTITY(agent.mainCenter) AS main_center')
            ->addSelect('IDENTITY(aside.type) AS aside_activity_type')
            ->addSelect('aside.date')
            ->addSelect('aside.duration')
            ->addSelect('IDENTITY(aside.location) AS location')
            ->addSelect('aside.note');

        return $qb;
    }

    public function requiredRole(): string
    {
        return AsideActivityVoter::STATS;
    }

    public function supportsModifiers()
    {
        return [Declarations::ASIDE_ACTIVITY_TYPE];
    }
}
