<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Controller;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Utility\Now;
use Neos\Neos\Domain\Service\ContentContext;
use Neos\Flow\Annotations as Flow;

class AbstractActionController extends ActionController
{

    /**
     * @var Node
     */
    protected $node;

    /**
     * @var array
     */
    protected $properties = [];

    /**
     * @Flow\InjectConfiguration
     * @var array
     */
    protected $configuration;

    /** @var string|null */
    protected $mimeType = null;

    /** @var int|null */
    protected $browserCacheLifetimeDays = null;

    /**
     * Action initializer.
     *
     * @return void
     */
    public function initializeAction()
    {
        /** @var Node|null $node */
        $node = $this->request->getInternalArgument('__node');
        if ($node instanceof Node) {
            $this->node = $node;
        }

        if ($this->node !== null) {
            $this->properties = (array) $this->node->getProperties();
        }

        if ($this->mimeType) {
            $this->response->setContentType($this->mimeType);
        }

        if ($this->browserCacheLifetimeDays) {
            $this->response->setHeader('Cache-Control', 'max-age=' . ($this->browserCacheLifetimeDays * 24 * 60 * 60));
            $interval = sprintf('P%dD', $this->browserCacheLifetimeDays);
            $this->response->setExpires(
                (new Now())->add(new \DateInterval($interval))->format(DATE_RFC822)
            );
        }
    }


    protected function callActionMethod(): void
    {
        try {
            parent::callActionMethod();
        } catch (\Throwable $e) {
            $this->handleError($e);
        }
    }

    protected function handleError(\Throwable $throwable): void
    {
        throw $throwable;
    }

    protected function isInBackend(): bool
    {
        $context = $this->node->getContext();
        if (!($context instanceof ContentContext)) {
            return false;
        }

        return $context->isInBackend();
    }
}
