<?php declare(strict_types=1);

namespace Newland\NeosIcons;

use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use function Safe\opendir;
use function Safe\file_get_contents;
use Neos\Flow\Annotations as Flow;

class IconUtility
{
    /**
     * @var array
     * @Flow\InjectConfiguration(path="directories")
     */
    protected $directories;

    /**
     * @return array<string, string>
     */
    public function listAllAvailableIcons(): array
    {
        $icons = [];

        foreach ($this->directories as $directory) {
            $dir = opendir($directory);
            // phpcs:ignore
            while ($icon = readdir($dir)) {
                if (str_starts_with($icon, '.')) {
                    continue;
                }
                $iconName = str_replace('.svg', '', $icon);
                $iconPath = sprintf('%s/%s', $directory, $icon);

                if (!array_key_exists($iconName, $icons)) {
                    $icons[$iconName] = $iconPath;
                }
            }
        }

        return $icons;
    }

    public function getIcon(string $name): Icon
    {
        $iconPath = $this->listAllAvailableIcons()[$name] ?? null;
        if (!$iconPath || !file_exists($iconPath)) {
            return $this->errorIcon(sprintf('Icon %s not found', $name));
        }
        return Icon::fromString(file_get_contents($iconPath));
    }

    public function errorIcon(string $message): Icon
    {
        $iconPath = $this->listAllAvailableIcons()['question'] ?? null;
        if (!$iconPath) {
            throw new InvalidConfigurationException('
                No `question` icon found. If you have customized Newland.ToubizIcons.directories,
                please ensure, that you have

                - At least the following icons: `question`, `map-marker`, `circle`
                - OR, you explicitly list `resource://Newland.NeosIcons/Private/Icons` as a directory in order to
                  fall back on those icons.
            ');
        }

        $contents = file_get_contents($iconPath);
        $contents .= '<!-- ' . $message . '-->';

        return Icon::fromString($contents);
    }
}
