<?php

namespace Newland\Toubiz\Poi\Neos\Service;

use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Domain\Filter\ArticleFilter;

/**
 * @Flow\Scope("singleton")
 */
class ArticleFilterService
{

    /**
     * @param array $topics
     * @param ArticleFilter $filter
     */
    public function setFilterFromTopics(array $topics, ArticleFilter $filter)
    {
        $categoriesToFilter = [];
        $attributesToFilter = [];
        foreach ($topics as $topic) {
            list($type, $id) = $this->extractTypeAndIdFromTopicIdentifier($topic);
            if (!$type || !$id) {
                continue;
            }
            switch ($type) {
                case 'category':
                    $categoriesToFilter[] = $id;
                    break;
                case 'attribute':
                    $attributesToFilter = $this->handleAttribute($id, $attributesToFilter);
                    break;
            }
        }
        $filter->setCategories($categoriesToFilter);
        $filter->setAttributesIn($attributesToFilter);
        return $filter;
    }


    /**
     * @param string $attributeString
     * @param array $attributesToFilter
     * @return array
     */
    private function handleAttribute(string $attributeString, array $attributesToFilter)
    {
        $exploded = explode(':', $attributeString);
        $attribute = $exploded[0];
        $value = \count($exploded) > 1 ? $exploded[1] : null;
        if (!array_key_exists($attribute, $attributesToFilter)) {
            $attributesToFilter[$attribute] = [$value];
        } else {
            $attributesToFilter[$attribute][] = $value;
        }
        return $attributesToFilter;
    }

    private function extractTypeAndIdFromTopicIdentifier(string $topic): array
    {
        $exploded = explode(':', $topic, 2);
        return [
            $exploded[0] ?? null,
            $exploded[1] ?? null
        ];
    }
}
