<?php
namespace library;

/**
 * Add extra macros, filters and functions for Latte
 * Implements the IFilter interface
 * @author Jerôme Brilland
 * @version 1.0
 * @copyright (c) 2022, 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();
            $set = new \Latte\Macros\MacroSet( $latte->getCompiler() );

            $set->addMacro(
                'snippet',
                '$snippet = models\\Snippet::findOne( [\'name\' => %node.word] );',
                'unset( $snippet )'
            );

            $set->addMacro(
                'snippetContent',
                'echo IoC::resolve( \'texy\')->process( models\\Snippet::findOne( [\'name\' => %node.word] )->content );'
            );

            $set->addMacro(
                'siteTitle',
                'echo IoC::resolve( \'settings\')[\'site_title\'];'
            );

            $set->addMacro(
                'executionTime',
                'echo microtime( true ) - START_TIME;'
            );
            
            $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 );
	}
}
