<?php

declare(strict_types=1);

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

namespace TYPO3\CMS\Backend\Controller;

use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Backend\Attribute\AsController;
use TYPO3\CMS\Backend\Search\Event\BeforeLiveSearchFormIsBuiltEvent;
use TYPO3\CMS\Backend\Search\LiveSearch\SearchDemand\SearchDemand;
use TYPO3\CMS\Backend\Search\LiveSearch\SearchRepository;
use TYPO3\CMS\Backend\View\BackendViewFactory;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Http\Response;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Pagination\SlidingWindowPagination;

/**
 * Returns the results for any live searches, e.g. in the toolbar
 * @internal This class is a specific Backend controller implementation and is not considered part of the Public TYPO3 API.
 */
#[AsController]
readonly class LiveSearchController
{
    public function __construct(
        protected BackendViewFactory $backendViewFactory,
        protected SearchRepository $searchService,
        protected EventDispatcherInterface $eventDispatcher,
    ) {}

    /**
     * Processes all AJAX calls and sends back a JSON object
     */
    public function searchAction(ServerRequestInterface $request): ResponseInterface
    {
        $mutableSearchDemand = SearchDemand::fromRequest($request);
        if ($mutableSearchDemand->getQuery() === '') {
            return new Response('', 400, [], 'Argument "query" is missing or empty.');
        }

        $results = $this->searchService->find($mutableSearchDemand);
        $pagination = new SlidingWindowPagination($results, 15);
        $response = [
            'pagination' => [
                'itemsPerPage' => SearchDemand::DEFAULT_LIMIT,
                'currentPage' => $pagination->getPaginator()->getCurrentPageNumber(),
                'firstPage' => $pagination->getFirstPageNumber(),
                'lastPage' => $pagination->getLastPageNumber(),
                'allPageNumbers' => $pagination->getAllPageNumbers(),
                'previousPageNumber' => $pagination->getPreviousPageNumber(),
                'nextPageNumber' => $pagination->getNextPageNumber(),
                'hasMorePages' => $pagination->getHasMorePages(),
                'hasLessPages' => $pagination->getHasLessPages(),
            ],
            'results' => $results->getPaginatedItems(),
        ];

        return new JsonResponse($response);
    }

    public function formAction(ServerRequestInterface $request): ResponseInterface
    {
        $hints = [
            'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:liveSearch_helpDescriptionPages',
            'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:liveSearch_helpDescriptionContent',
            'LLL:EXT:core/Resources/Private/Language/locallang_misc.xlf:liveSearch_help.shortcutOpen',
        ];

        $event = $this->eventDispatcher->dispatch(
            new BeforeLiveSearchFormIsBuiltEvent($hints, $request)
        );
        $hints = $event->getHints();
        $searchDemand = $event->getSearchDemand();
        $randomHintKey = array_rand($hints);
        $additionalViewData = $event->getAdditionalViewData();

        $searchProviders = $this->searchService->getSearchProviderState($searchDemand);

        $activeOptions = 0;
        // `isActive` is the result of `in_array()`, which returns a `bool`.
        $activeOptions += count(array_filter($searchProviders, fn(array $searchProviderOption): bool => $searchProviderOption['isActive']));

        $view = $this->backendViewFactory->create($request, ['typo3/cms-backend']);
        if ($additionalViewData !== []) {
            $view->assignMultiple($additionalViewData);
        }
        $view->assignMultiple([
            'searchDemand' => $searchDemand,
            'hint' => $this->getLanguageService()->sL($hints[$randomHintKey]),
            'searchProviders' => $searchProviders,
            'activeOptions' => $activeOptions,
        ]);

        $response = new Response();
        $response->getBody()->write($view->render('LiveSearch/Form'));

        return $response;
    }

    private function getLanguageService(): LanguageService
    {
        return $GLOBALS['LANG'];
    }
}
