<?php declare(strict_types=1);

namespace Newland\Toubiz\Services\Neos\DataSource;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ServiceRepository;

class ServiceDataSource extends AbstractDataSource
{
    protected static $identifier = 'newland-toubiz-services-neos-services';

    /**
     * @var ServiceRepository
     * @Flow\Inject()
     */
    protected $serviceRepository;

    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        return $this->serviceRepository->withLanguage(
            $arguments['language'] ?? null,
            function () use ($arguments) {
                $query = $this->query();

                if (array_key_exists('type', $arguments)) {
                    $query->where($query->expr()->eq('service.type', ':type'));
                    $query->setParameter('type', $arguments['type']);
                }

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

    private function query(): QueryBuilder
    {
        return $this->serviceRepository
            ->createQueryBuilder('service')
            ->select(
                [
                    'service.name as label',
                    'service.Persistence_Object_Identifier as value',
                ]
            );
    }
}
