<?php
class CDTimber extends Timber {
	/** Add timber support. */
	public function __construct() {
		add_action( 'after_setup_theme', array( $this, 'theme_supports' ) );
		//add_filter( 'timber_context', array( $this, 'add_to_context' ) );
		add_filter( 'get_twig', array( $this, 'add_to_twig' ) );
		parent::__construct();
	}

	/** This is where you add some context
	 *
	 * @param string $context context['this'] Being the Twig's {{ this }}.
	 */

	public static function get_context($args = null){
		$context = Timber::get_context();
		$context['_post'] = $_POST;
		$context['_get'] = $_GET;
		$context['_session'] = $_SESSION;

		global $wp_query;

		if( !( isset($args['no_query']) && $args['no_query'] == true ) ){
			if ( is_singular() ){
				if($args){
					$context['post'] = new TimberPost($args);
				}else{
					$context['post'] = new TimberPost();
				}
			}else{
				if($args){
					$context['posts'] = new Timber\PostQuery($args);
				}else{
					$context['posts'] = new Timber\PostQuery();
				}

			}
		}
		return $context;
	}

	public function add_to_context( $context, $args = null ) {
		$context['site'] = $this;
		return $context;
	}

	public function theme_supports() {
		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support( 'title-tag' );

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5', array(
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
			)
		);

		/*
		 * Enable support for Post Formats.
		 *
		 * See: https://codex.wordpress.org/Post_Formats
		 */
		add_theme_support(
			'post-formats', array(
				'aside',
				'image',
				'video',
				'quote',
				'link',
				'gallery',
				'audio',
			)
		);

		add_theme_support( 'menus' );
	}

	/** This is where you can add your own functions to twig.
	 *
	 * @param string $twig get extension.
	 */
	public function add_to_twig( $twig ) {
		$twig->addExtension( new Twig_Extension_StringLoader() );
		return $twig;
	}

	public static function compile($filenames, $data = Array(), $expires = false, $cache_mode = Timber\Loader::CACHE_USE_DEFAULT, $via_render = false) {
  	return parent::compile($filenames, $data , $expires, $cache_mode, $via_render);
  }

}
?>
