<?php

namespace Dispatch\Config;

use Timber;
use Timber\Helper as TimberHelper;
use fewbricks\bricks as bricks;

class FewBricks {

    public function __construct() {

        add_filter( 'dispatch_add_to_context', [$this, 'add_to_context'] );

    }

    public function add_to_context( $context ) {

        TimberHelper::function_wrapper( array( $this, 'fewbricks_brick' ), array( false, false, false ) );
        TimberHelper::function_wrapper( array( $this, 'panels' ), array( array() ) );
        TimberHelper::function_wrapper( array( $this, 'panels_navigation' ), array( array() ) );

        return $context;

    }

    public function panels_navigation( $panels = array() ) {

        $data = array(
                'panels' => $panels
            );

        Timber::render('components/common/panels-navigation.twig', $data);

    }

    public function panels( $panels = array() ) {

        foreach ($panels as $panel) {
            $args = array(
                    'title' => $panel['title'],
                    'key' => $panel['key']
                );
            $this->panel( $panel['brick_type'], $panel['brick_key'], $args );
        }

    }

    public function panel( $brick_type, $brick_key, $args = array(), $layout = null ) {
        if ( !$brick_type || !$brick_key ) return false;
        eval('$brick = (new \fewbricks\bricks\\' . $brick_type . '("' . $brick_key . '"));');
        echo $brick->get_html( $args, $layout );
    }

    public function fewbricks_brick( $brick_type, $brick_key, $layout = null ) {
        if ( !$brick_type || !$brick_key ) return false;
        if ( !$layout ) {
            eval('echo (new \fewbricks\bricks\\' . $brick_type . '("' . $brick_key . '"))->get_html();');
        } else {
            eval('echo (new \fewbricks\bricks\\' . $brick_type . '("' . $brick_key . '"))->get_html(false,"' . $layout . '");');
        }
    }

}
