<?php
namespace Newland\PageFrameProvider\Definition;

use Newland\PageFrameProvider\Utility\ArrayUtility;

class RouteDefinition
{
    const FALLBACK_SEGMENT = '_fallback';
    const FALLBACK_SITE = '_fallback';

    /** @var string[][] */
    private $uriSegments;

    /** @var array */
    private $breadcrumb;

    /**
     * @param string|array $config
     */
    public function __construct($config)
    {
        if (\is_string($config)) {
            $config = [ 'uriSegment' => [ static::FALLBACK_SEGMENT => $config ] ];
        }

        if (\is_string($config['uriSegment'])) {
            $config['uriSegment'] = [ static::FALLBACK_SEGMENT => $config['uriSegment'] ];
        }

        $this->breadcrumb = $config['breadcrumb'] ?? [];
        $this->uriSegments = array_map(
            function (string $uri) {
                return trim($uri, '/');
            },
            $config['uriSegment'] ?? []
        );
    }

    public function getUriSegment(string $language = null)
    {
        return $this->uriSegments[$language]
            ?? $this->uriSegments[static::FALLBACK_SEGMENT]
            ?? null;
    }

    public function getUriSegments(): array
    {
        return $this->uriSegments;
    }

    public function getBreadcrumb(?string $siteNodeName = null): array
    {
        // Last condition is for legacy configuration purposes in order to support old
        // configuration.
        // TODO Remove last fallback with next major release.
        return $this->breadcrumb[$siteNodeName]
            ?? $this->breadcrumb[static::FALLBACK_SITE]
            ?? ArrayUtility::removeAssociativeArrayItems($this->breadcrumb);
    }
}
