<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Fusion\Core\Cache\ContentCache;
use Newland\Contracts\Neos\Filter\FilterRoot;
use Newland\Toubiz\Poi\Neos\Filter\ArticleFilterFactory;
use Newland\Toubiz\Poi\Neos\Filter\Items\ArticleRoot;
use Newland\Toubiz\Sync\Neos\Configuration\ConfigurationAction;
use Newland\Toubiz\Sync\Neos\Configuration\ConfigurationProvider as ConfigurationProviderInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Enum\ArticleType;
use Neos\Flow\Annotations as Flow;

class ConfigurationProvider implements ConfigurationProviderInterface
{

    /**
     * @var ContentCache
     * @Flow\Inject()
     */
    protected $contentCache;

    /** @var string */
    protected $type;

    /** @return string[] */
    public function types(): array
    {
        return ArticleType::values();
    }

    public function filter(NodeInterface $node): FilterRoot
    {
        $articleType = array_flip(ArticleType::$map)[$this->type];
        return (new ArticleFilterFactory($node))->createFilterForArticleType($articleType, []);
    }

    /** @param ArticleRoot $filter */
    public function count(FilterRoot $filter): int
    {
        return $filter->countArticles([], true);
    }

    /** @param ArticleRoot $filter */
    public function fetch(FilterRoot $filter): array
    {
        return $filter->getArticleQuery([], true)->getQuery()->execute();
    }

    /**
     * Converts the given fetched item to table items: An array of primitive values displayed in the table.
     * @param Article $item
     */
    public function tableItems($item): array
    {
        return [
            sprintf('<small>%s</small>', $item->getOriginalId()),
            $item->getName(),
        ];
    }

    /**
     * @param Article $item
     * @return ConfigurationAction[]
     */
    public function actions($item): array
    {
        return [
            'hide' => new ConfigurationAction(
                $item->isHidden() ? 'anzeigen' : 'verbergen',
                $item->isHidden() ? 'fas fa-eye-slash' : 'fas fa-eye',
                $item->isHidden() ? 'red' : 'green',
                function (array $configuration) {
                    $this->contentCache->flushByTag('article');
                    $configuration['hidden'] = !($configuration['hidden'] ?? false);
                    return $configuration;
                }
            )
        ];
    }

    public function setType(string $type): void
    {
        $this->type = $type;
    }
}
