<?php declare(strict_types=1);

namespace Newland\Toubiz\Search\Neos\DataSource;

/*
 * This file is part of the "toubiz-search-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\I18n\Translator;
use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Neos\Service\DataSource\AbstractDataSource;

/**
 * Categories data source service.
 *
 * @Flow\Scope("singleton")
 */
class AvailableTypesDataSource extends AbstractDataSource
{
    /**
     * Data source identifier.
     *
     * @var string
     */
    protected static $identifier = 'newland-toubiz-search-neos-types';

    /**
     * @var ConfigurationManager
     * @Flow\Inject()
     */
    protected $configurationManager;

    /**
     * @var Translator
     * @Flow\Inject()
     */
    protected $translator;

    /**
     * Get requested data from source.
     *
     * The return value must be JSON serializable data structure.
     *
     * @api
     * @param NodeInterface $node The node that is currently edited (optional)
     * @param array $arguments Additional arguments (key / value)
     * @return mixed JSON serializable data
     * @throws \Neos\ContentRepository\Exception\NodeException
     */
    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        $availableTypes = $this->configurationManager->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            'Newland.Toubiz.Search.Neos.availableTypes'
        );

        if (!\is_array($availableTypes)) {
            return [];
        }

        $data = [];
        foreach ($availableTypes as $type => $isEnabled) {
            if ($isEnabled) {
                $data[] = [
                    'value' => $type,
                    'label' => $this->translate('properties.preselectedTypes.selectBoxEditor.values.' . $type),
                ];
            }
        }

        return $data;
    }

    private function translate(string $id): string
    {
        return (string) $this->translator->translateById(
            $id,
            [],
            null,
            null,
            'NodeTypes/Search',
            'Newland.Toubiz.Search.Neos'
        );
    }
}
