<?php declare(strict_types=1);

namespace Newland\NeosIcons\Controller;

use Neos\Flow\Annotations as Flow;
use Newland\NeosCommon\Controller\AbstractApiController;
use Newland\NeosIcons\IconUtility;

class SvgController extends AbstractApiController
{
    protected const MARKER_BASE_ICON = 'map-marker';
    protected $mimeType = 'image/svg+xml';

    /** @var int */
    protected $browserCacheLifetimeDays = 14;

    /**
     * @var array
     * @Flow\InjectConfiguration(path="icons")
     */
    protected $iconSettings;

    /**
     * @var IconUtility
     * @Flow\Inject()
     */
    protected $iconUtility;
    protected function handleError(\Throwable $throwable): void
    {
        $message = sprintf(
            "%s\n%s:%s\n\n%s",
            $throwable->getMessage(),
            $throwable->getFile(),
            $throwable->getLine(),
            $throwable->getTraceAsString()
        );
        $content = $this->iconUtility->errorIcon($message)->toString();
        $this->response->setStatusCode(500);
        $this->response->setContent($content);
    }

    public function mapMarkerAction(string $icon, string $foregroundColor, string $backgroundColor): string
    {
        $symbol = $this->iconUtility->getIcon($icon)->fill($foregroundColor);
        return $this->iconUtility
            ->getIcon(static::MARKER_BASE_ICON)
            ->fill($backgroundColor)
            ->overlayIcon(
                $symbol,
                $this->iconSettings[$icon]['x'] ?? $this->iconSettings['_default']['x'] ?? 90,
                $this->iconSettings[$icon]['y'] ?? $this->iconSettings['_default']['y'] ?? -75,
                $this->iconSettings[$icon]['width'] ?? $this->iconSettings['_default']['width'] ?? 200,
                $this->iconSettings[$icon]['height'] ?? $this->iconSettings['_default']['height'] ?? null
            )
            ->toString();
    }
}
