<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Twig\DataProvider;

use KupShop\ComponentsBundle\Twig\Components\Articles\List\Article;
use KupShop\ComponentsBundle\Twig\Components\Breadcrumbs;
use KupShop\ComponentsBundle\Twig\Components\Product;
use KupShop\ComponentsBundle\Twig\Components\Recommender;

class MicrodataProvider
{
    public const ARTICLE = Article::class;
    public const PRODUCT = Product\View::class;
    public const BREADCRUMBS = Breadcrumbs::class;
    public const RECOMMENDER = Recommender::class;

    public static $scopes = [
        Product\View::class => self::PRODUCT,
        Breadcrumbs::class => self::BREADCRUMBS,
        Article::class => self::ARTICLE,
        Recommender::class => self::RECOMMENDER,
    ];

    protected array $microdata = [];

    protected array $activeScopes = [];

    public function appendData(array $microdata): void
    {
        $this->microdata = array_merge_recursive($this->microdata, $microdata);
    }

    public function getJsonsArray(): array
    {
        $array = array_map(function ($microdata) {
            return json_encode($microdata, JSON_NUMERIC_CHECK | JSON_HEX_APOS | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        }, array_filter($this->microdata));

        return $array;
    }

    public function setActiveScope(string $scope)
    {
        $this->activeScopes[] = $scope;
    }

    public function getActiveScope(): ?string
    {
        if (empty($this->activeScopes)) {
            return null;
        }

        return end($this->activeScopes);
    }

    public function disableActiveScope()
    {
        array_pop($this->activeScopes);
    }
}
