<?php
namespace Newland\PageFrameProvider\Controller;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Neos\View\FusionView;
use Newland\PageFrameProvider\Breadcrumb\BreadcrumbImplementation;
use Newland\PageFrameProvider\Service\ComponentCommunicationService;
use Newland\PageFrameProvider\Service\PageFrameContextService;
use Newland\PageFrameProvider\Service\PageFrameLinkingService;
use Neos\Flow\Annotations as Flow;

/**
 * Renders the page frame with a custom plugin as content.
 * @see PageFrameLinkingService
 *
 * @property FusionView $view
 */
class PageFrameController extends ActionController
{
    /** @var string */
    protected $defaultViewObjectName = FusionView::class;

    /**
     * @var PageFrameContextService
     * @Flow\Inject()
     */
    protected $pageFrameContext;

    /**
     * @var array
     * @Flow\InjectConfiguration("breadcrumb")
     */
    protected $breadcrumbConfiguration;

    /**
     * @var array
     * @Flow\InjectConfiguration("alternativeDimensions")
     */
    protected $alternativeDimensionsConfiguration;

    public function showAction(Node $node, string $pageFrame = 'default')
    {
        $this->pushContext($pageFrame, $node);
        $this->view->setFusionPath('pageFrame/' . $pageFrame);
        $this->view->assignMultiple([ 'value' => $node ]);
    }

    private function pushContext(string $pageFrame, Node $node)
    {
        $this->pageFrameContext->setNode($node);
        $this->pageFrameContext->setPluginArguments(
            $this->request->getPluginArguments()['plugin'] ?? []
        );
        $this->pageFrameContext->setBreadcrumbConfig($this->getBreadCrumbConfiguration($pageFrame));
        $this->pageFrameContext->setAlternativeDimensionsConfig(
            $this->getAlternativeDimensionConfiguration($pageFrame)
        );
    }

    private function getBreadCrumbConfiguration(string $pageFrame)
    {
        if (!$this->breadcrumbConfiguration || !array_key_exists($pageFrame, $this->breadcrumbConfiguration)) {
            return [];
        }

        return $this->breadcrumbConfiguration[$pageFrame];
    }

    private function getAlternativeDimensionConfiguration(string $pageFrame)
    {
        if (!$this->alternativeDimensionsConfiguration
            || !array_key_exists($pageFrame, $this->alternativeDimensionsConfiguration)
        ) {
            return [];
        }

        return $this->alternativeDimensionsConfiguration[$pageFrame];
    }
}
