<?php

namespace YOOtheme\Demo\Routes;

use Joomla\CMS\Factory;
use YOOtheme\Builder;
use YOOtheme\Http\Request;
use function YOOtheme\app;

class ScreenshotStyle
{
    public static function match(Request $request)
    {
        return $request->getQueryParam('screenshotStyle');
    }

    public static function handle($demo)
    {
        $layout = file_get_contents($demo['demoDir'] . '/.cache/screenshot/style.json');

        $app = Factory::getApplication();
        $app->getDispatcher()->addListener('onAfterDispatch', function () use ($layout) {
            $builder = app(Builder::class);
            $layout = $builder->render($layout);

            Factory::getApplication()
                ->getDocument()
                ->addStyleDeclaration(
                    '.tm-toolbar, .tm-header, .tm-header-placeholder, .builder[id^="module-"], footer, main ~ * {display: none !important;}'
                )
                ->setBuffer($layout, [
                    'type' => 'component',
                    'name' => null,
                    'title' => null,
                ]);
        });

        // Set theme name in headline
        app()->extend(Builder::class, function ($builder) use ($demo) {
            $builder->addTransform('render', function ($node) use ($demo) {
                if ($node->type === 'headline' && $node->props['title_element'] === 'h1') {
                    $node->props['content'] = ucwords(str_replace('-', ' ', $demo['theme']));
                }
            });
        });
    }
}
