<?php
declare(strict_types=1);

namespace ProudNerds\Block;

use Timber\Post;
use Timber\Timber;
use ProudNerds\Block\ContextBuilder;

final class AcfBlockRenderer
{


    /**
     * @var ContextBuilder
     */
    private $contextBuilder;

    public function __construct()
    {
        $this->contextBuilder = new ContextBuilder();
    }

    public function __invoke(array $blockData, $content = '', $isPreview = false, $postId = false): void
    {
        /** @var Block $block */
        $block = $blockData['_block'];

        unset(
            $blockData['_block'],
            $blockData['render_callback']
        );

        if ($postId === false) {
            echo \sprintf('<pre style="color:#c92c2c;font-size:12px">Error rendering block "%s".No postId is given.</pre>', $block->getTitle());
            return;
        }
        $meta = $blockData;
        unset($meta['data']);
        $meta['preview'] = $isPreview;
        $meta['slug' ] = $block->getSlug();

        $context = $this->contextBuilder->build(
            $block,
            Timber::get_post($postId),
            [
                'meta' => $meta,
            ]
        );

        $templateFile = sprintf('views/blocks/%s.twig', $block->getSlug());

        $rendered = Timber::render($templateFile, $context->toArray());

        if (!$rendered && is_admin()) {
            echo \sprintf('<pre style="color:#c92c2c;font-size:12px">Error rendering block "%s". Please make sure the template file "%s" is present.</pre>', $block->getTitle(), $templateFile);
        }
    }
}
