<?php
namespace Wpupgrader\Libraries\WordPress\Plugins\Core\Blocks;

use Wpupgrader\Libraries\WordPress\Plugins\Core\BaseConfig;
use Wpupgrader\Libraries\WordPress\Plugins\Core\ConfigTrait;

abstract class Block
{
    use ConfigTrait;

    public $template;
    protected $values = [];
    private $name;

    public function __construct(BaseConfig &$config, $name)
    {
        $this->setConfig($config);
        $this->name = $name;
    }

    public function render($parseshortcodes = false)
    {
        \ob_start();
        include $this->getConfig()->get('source_path').'/Hooks/Templates/'.$this->name.'.php';
        $contents = \ob_get_contents();
        \ob_end_clean();

        $contents = ($parseshortcodes) ? \do_shortcode($contents) : $contents;

        return $contents;
    }

    public function getHtml($file, $params = [], $default = false)
    {
        $calledFile = \debug_backtrace()[0]['file'];

        \extract($params);

        \ob_start();
        $file = \dirname($calledFile).'/'.$file.'.php';

        if (!\file_exists($file) && $default) {
            $file = \dirname($calledFile).'/'.$default.'.php';
        }

        include $file;
        $contents = \ob_get_contents();
        \ob_end_clean();

        return $contents;
    }

    public function getChildHtml($child, $params = [], $default = false)
    {
        $calledFile = \debug_backtrace()[0]['file'];

        \extract($params);

        \ob_start();
        $file = \dirname($calledFile).'/'.\pathinfo($calledFile, PATHINFO_FILENAME).'/'.$child.'.php';

        if (!\file_exists($file) && $default) {
            $file = \dirname($calledFile).'/'.\pathinfo($calledFile, PATHINFO_FILENAME).'/'.$default.'.php';
        }

        include $file;
        $contents = \ob_get_contents();
        \ob_end_clean();

        return $contents;
    }

    public function __call($methodName, $params = null)
    {
        $methodPrefix = \substr($methodName, 0, 3);
        $key = \strtolower(\substr($methodName, 3));

        if ($methodPrefix == 'get') {
            return isset($this->values[$key]) ? $this->values[$key] : false;
        }

        if ($methodPrefix == 'set' && isset($params[0])) {
            $this->values[$key] = $params[0];
            return;
        }

        throw new \Exception($methodName.' does not exists');
    }

    private function getTemplate()
    {
        if (!$this->template) {
            throw new \Exception('Undefined template');
        }
    }
}