<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Controller;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Map\Neos\Provider\Contract\ProviderContext;
use Newland\Toubiz\Map\Neos\Provider\MapDataProviderService;
use Newland\Toubiz\Sync\Neos\Translation\CurrentLanguageService;
use function Safe\json_encode;

class ApiController extends AbstractActionController
{
    protected $mimeType = 'application/json';

    /**
     * @var MapDataProviderService
     * @Flow\Inject()
     */
    protected $mapDataProviderService;

    /**
     * @var CurrentLanguageService
     * @Flow\Inject()
     */
    protected $currentLanguageService;

    protected function handleError(\Throwable $throwable): void
    {
        $this->response->setStatusCode(500);
        $this->response->setContent(
            json_encode(
                [
                    'error' => [
                        'code' => $throwable->getCode(),
                        'file' => $throwable->getFile(),
                        'line' => $throwable->getLine(),
                        'message' => $throwable->getMessage(),
                        'trace' => $throwable->getTrace(),
                    ],
                ]
            )
        );
    }

    public function markerListAction(Node $node, int $page): string
    {
        $this->updateLanguage($node);

        $paginator = $this->mapDataProviderService->getMarkers($this->context($node));


        return json_encode([
            '_pagination' => [
                'items' => $paginator->numberOfItems(),
                'pages' => $paginator->numberOfPages(),
            ],
            'payload' => $paginator->get($page),
        ]);
    }

    public function filterItemListAction(Node $node): string
    {
        $this->updateLanguage($node);
        return json_encode($this->mapDataProviderService->getFilterItems($this->context($node)));
    }

    private function context(Node $node): ProviderContext
    {
        return new ProviderContext(
            $node,
            $this->request->getHttpRequest()
        );
    }

    private function updateLanguage(Node $node): void
    {
        $language = $node->getDimensions()['language'][0] ?? null;
        if ($language) {
            $this->currentLanguageService->updateLanguage((string) $language);
        }
    }
}
