<?php

namespace Slovocast;

use League\Config\Configuration;
use Odan\Session\SessionInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Slim\App;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\Error\LoaderError;

class Middlewares
{
    /**
     * @throws NotFoundExceptionInterface
     * @throws ContainerExceptionInterface
     * @throws LoaderError
     */
    public static function setup(App $app): void
    {
        /** @var ContainerInterface $container */
        $container = $app->getContainer();

        /**
         * @var Configuration $config
         */
        $config = $container->get('config');

        // Twig
        $templateCache = false;
        $twig = Twig::create(APP_TEMPLATES_DIR, [ 'cache' => $templateCache ]);

        // Add the global variables
        $twig->getEnvironment()->addGlobal('site_name', $config->get('site.name'));
        $twig->getEnvironment()->addGlobal('site_description', $config->get('site.description'));
        $flash = $container->get(SessionInterface::class)->getFlash();
        $twig->getEnvironment()->addGlobal('flash', $flash);
        $app->add(TwigMiddleware::create($app, $twig));

        // Add the error handling middleware
        $app->addErrorMiddleware(true, true, true);
    }
}