<?php
declare(strict_types=1);

namespace ProudNerds\Block;


final class AcfBlockRegistrar
{
    /**
     * @var AcfBlockRenderer
     */
    private $renderer;

    /**
     * @var Block[]
     */
    private $blocks;

    /**
     * @param Block[] $blocks
     */
    public function __construct(AcfBlockRenderer $renderer, array $blocks)
    {
        $this->renderer = $renderer;
        $this->blocks = $blocks;
    }

    public function __invoke(): void
    {
        foreach ($this->blocks as $block) {
            if (!preg_match('/^[a-z-]+$/', $block->getSlug())) {
                throw new \Error('Invalid slug');
            }

            if( function_exists('acf_register_block_type') ) {
                acf_register_block_type([
                    '_block' => $block,
                    'name' => $block->getSlug(),
                    'title' => $block->getTitle(),
                    'description' => $block->getDescription(),
                    'category' => $block->getCategory(),
                    'icon' => $this->createIconDefinition($block),
                    'keywords' => $block->getKeywords(),
                    'mode' => 'preview',
                    'post_types' => $block->getAllowedPostTypes(),
                    'supports' => [
                        'align' => false,
                        'html' => false,
                        'anchor' => true,
                        'mode' => $block->hasModeSwitch(),
                        'jsx' => $block->enableJSX(),
                    ],
                    'render_callback' => $this->renderer,
                ]);
            }
        }
    }

    private function createIconDefinition(Block $block): array
    {
        $icon = [
            'src' => $block->getIcon(),
        ];

        $color = $block->getIconBackgroundColor() ?? '#FFFFFF';

        if ($color) {
            $icon['background'] = $color;
        }

        return $icon;
    }
}

