<?php
namespace Newland\Toubiz\Map\Neos\DataSource;

/*
 * This file is part of the "toubiz-map-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\Persistence\PersistenceManagerInterface;
use Neos\Neos\Service\DataSource\AbstractDataSource;

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

    /**
     * @Flow\InjectConfiguration
     * @var array
     */
    protected $configuration;

    /**
     * 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
     */
    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        $data = [];
        foreach ($this->configuration['categories'] as $parentCategory) {
            if ($parentCategory['children']) {
                foreach ($parentCategory['children'] as $childCategory) {
                    $data[] = [
                        'label' => $childCategory['label'],
                        'value' => $childCategory['value'],
                        'group' => $parentCategory['label'],
                    ];
                }
            } else {
                $data[] = [
                    'label' => $parentCategory['label'],
                    'value' => $parentCategory['value'],
                ];
            }
        }
        return $data;
    }
}
