<?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
{

    public function setFilterFromTopics(array $topics, ArticleFilter $filter): ArticleFilter
    {
        $categoriesToFilter = [];
        $attributesToFilter = [];
        foreach ($topics as $topic) {
            [$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;
    }


    private function handleAttribute(string $attributeString, array $attributesToFilter): array
    {
        $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
        ];
    }
}
