<?php
namespace Newland\Toubiz\Events\Neos\LinkHandler;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Mvc\Controller\ControllerContext;
use Newland\NeosCommon\LinkHandler\Domain\Model\Record;
use Newland\NeosCommon\LinkHandler\Handler\AbstractLinkHandler;
use Newland\Toubiz\Events\Neos\Service\EventUrlService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventRepository;
use Neos\Flow\Annotations as Flow;

class EventLinkHandler extends AbstractLinkHandler
{

    /**
     * @var EventRepository
     * @Flow\Inject()
     */
    protected $eventRepository;

    /**
     * @var EventUrlService
     * @Flow\Inject()
     */
    protected $eventUrlService;

    /**
     * Generates a record link for the given record.
     *
     * @param Record $record
     * @param ControllerContext $controllerContext
     * @param NodeInterface $contextNode
     * @param bool $absolute
     * @return string|null
     */
    public function generateRecordLink(
        Record $record,
        ControllerContext $controllerContext,
        NodeInterface $contextNode,
        bool $absolute
    ): ?string {
        if (!($record instanceof EventRecord)) {
            $record = $this->findByIdentifier($record->getId());
        }

        if ($record === null) {
            return null;
        }

        return $this->eventUrlService->generateUrl(
            $record->getEvent(),
            $controllerContext,
            $contextNode
        );
    }

    /**
     * @param string $recordIdentifier
     * @return EventRecord|null
     */
    public function findByIdentifier(string $recordIdentifier): ?Record
    {
        $event = $this->eventRepository->withLanguage($this->language, function () use ($recordIdentifier) {
            return $this->eventRepository->findByIdentifier($recordIdentifier);
        });
        return $this->eventToRecord($event);
    }

    /**
     * @param string $searchTerm
     * @return Record[]
     */
    public function findBySearchTerm(string $searchTerm): array
    {
        return $this->eventRepository->withLanguage($this->language, function () use ($searchTerm) {
            $query = $this->eventRepository->createQueryBuilder('event');
            $query->where($query->expr()->like('event.title', ':searchTerm'));
            $query->setParameter('searchTerm', '%' . $searchTerm . '%');
            $query->setMaxResults(10);

            $records = [];
            foreach ($query->getQuery()->execute() as $event) {
                $record = $this->eventToRecord($event);
                if ($record !== null) {
                    $records[] = $record;
                }
            }

            return $records;
        });
    }

    private function eventToRecord(Event $event = null): ?EventRecord
    {
        if ($event === null) {
            return null;
        }
        return new EventRecord($event);
    }
}
