<?php
namespace library;

/**
 * Add extra tags, filters and functions for Latte
 * Implements the IFilter interface
 * @author Jerôme Brilland
 * @version 1.1
 * @copyright (c) 2022-2023, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class LatteFilter implements \IFilter {
  
	/**
	 * @param Request request Request object
	 * @param Response response Response object
	 * @access public
	 */
	public function execute( \Request $request, \Response $response, \FilterChain $filterchain ) {
        \IoC::resolve( 'eventmediator' )->attach( 'before_render', function( $controller, $request, $response ) {
            $latte = \IoC::resolve( 'view' )->getLatte();

            $latte->addFunction( 'snippet', function( $name ) {
                return \models\Snippet::findOne( ['name' => $name] );
            } );

            $latte->addFunction( 'snippetContent', function( $name ) {
                return new \Latte\Runtime\Html( \IoC::resolve( 'texy')->process( \models\Snippet::findOne( ['name' => $name] )->content ) );
            } );

            $latte->addFunction( 'siteTitle', function() {
                return \IoC::resolve( 'settings')['site_title'];
            } );

            $latte->addFunction( 'executionTime', function() {
                return microtime( true ) - START_TIME;
            } );
            
            $latte->addFunction( 'backendMenu', function() {
                $menuBuilder = \IoC::resolve( 'menubuilder' );
                return $menuBuilder->backendMenu();
            });
            
            $latte->addFunction( 'languageNames', function() {
                return \JSONHandler::decode( file_get_contents( CONFIG_DIR . 'languages.json' ), true );
            } );
            
            $latte->addFunction( 'pageTitlesExcept', function( $page ) {
                return array_column( \models\Page::findMany( ['page_id', 'title'], ['page_id[!]' => $page->page_id] ), 'title', 'page_id' );
            } );

            return true;
        } );
        
		$filterchain->execute( $request, $response );
	}
}
