<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Provider\Contract;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Http\Request;
use Neos\Flow\Http\Uri;

class ProviderContext
{
    /** @var Node */
    protected $mapNode;

    /** @var Request */
    protected $request;

    public function __construct(Node $mapNode, ?Request $request)
    {
        if (!$mapNode->getNodeType()->isOfType('Newland.Toubiz.Map.Neos:Map')) {
            throw new \InvalidArgumentException(sprintf(
                'Node must be of type `Newland.Toubiz.Map.Neos:Map` but is of type %s',
                $mapNode->getNodeType()->getName()
            ));
        }

        $this->mapNode = $mapNode;
        $this->request = $request
            ?? $this->createRequestFromHttpEnvironment()
            ?? $this->createPlaceholderRequestForCliEnvironments();
    }

    public function mapNode(): Node
    {
        return $this->mapNode;
    }

    public function request(): Request
    {
        return $this->request;
    }

    private function createRequestFromHttpEnvironment(): ?Request
    {
        if (!isset($_SERVER['HTTP_HOST'])) {
            return null;
        }

        $url = sprintf(
            '%s://%s%s',
            (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http',
            $_SERVER['HTTP_HOST'],
            $_SERVER['REQUEST_URI']
        );

        return Request::create(new Uri($url), $_SERVER['REQUEST_METHOD'], $_GET, $_FILES, $_SERVER);
    }

    private function createPlaceholderRequestForCliEnvironments(): Request
    {
        return Request::create(new Uri('https://placeholder'));
    }
}
