<?php declare(strict_types=1);
namespace Newland\Toubiz\Poi\Neos\DataSource;

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

use Doctrine\ORM\Query;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\PersistenceManagerInterface;
use Neos\Neos\Service\DataSource\AbstractDataSource;
use Newland\NeosCommon\Translation\LanguageAwareDataSource;

use Newland\Toubiz\Api\ObjectAdapter\Concern\ArticleConstants;
use Newland\Toubiz\Sync\Neos\Domain\Model\Attribute;
use Newland\Toubiz\Sync\Neos\Domain\Repository\AttributeRepository;
use Newland\Toubiz\Sync\Neos\Domain\Repository\CategoryRepository;

/**
 * Categories data source service.
 *
 * @Flow\Scope("singleton")
 */
class TagAttributesDataSource extends AbstractDataSource
{
    use LanguageAwareDataSource;

    /**
     * @var string Data source identifier.
     */
    protected static $identifier = 'newland-toubiz-poi-neos-tag-attributes';

    /**
     * @Flow\Inject()
     * @var AttributeRepository
     */
    protected $attributeRepository;

    /**
     * @Flow\Inject()
     * @var PersistenceManagerInterface
     */
    protected $persistenceManager;

    /**
     * Get requested data from source.
     *
     * The return value must be JSON serializable data structure.
     *
     * @param NodeInterface $node The node that is currently edited (optional)
     * @param array $arguments Additional arguments (key / value)
     * @return mixed JSON serializable data
     * @api
     */
    public function getData(NodeInterface $node = null, array $arguments = [])
    {
        $type = '';
        if ($node !== null && $node->hasProperty('articleType')) {
            $type = $node->getProperty('articleType');
        } elseif (array_key_exists('articleType', $arguments)) {
            $type = $arguments['articleType'];
        }

        $tags = $this->attributeRepository->getAllTagsByArticleType(
            (int) $type ?? ArticleConstants::TYPE_ATTRACTION
        );

        return $this->toDataSourceFormat($tags);
    }

    /** @return string[][] */
    public function toDataSourceFormat(array $tags): array
    {
        $data = [];
        foreach ($tags as $tag) {
            $data[] = [
                'value' => 'tag:' . $tag['data'],
                'label' => $tag['data'],
            ];
        }
        return $data;
    }
}
