<?php

namespace FiloBlu\Esb\Framework\Template;

use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;

use function is_array;
use function is_string;

/**
 * Class Template
 * @package FiloBlu\Esb\Framework\Template
 */
class SimpleTemplate implements TemplateInterface
{

    /**
     * @var array
     */
    protected $template = [];

    /**
     * @var array
     */
    protected $variables = [];

    /**
     * @var DataObjectFactory
     */
    private $dataObjectFactory;


    /**
     * Template constructor.
     * @param DataObjectFactory $dataObjectFactory
     */
    public function __construct(
        DataObjectFactory $dataObjectFactory
    ) {
        $this->dataObjectFactory = $dataObjectFactory;
    }

    /**
     * @param array $variables
     * @return TemplateInterface
     */
    public function setVariables(array $variables): TemplateInterface
    {
        $this->variables = $variables;
        return $this;
    }

    /**
     * @param array $template
     * @return TemplateInterface
     */
    public function setTemplate(array $template): TemplateInterface
    {
        $this->template = $template;
        return $this;
    }

    /**
     * @return DataObject
     */
    public function render(): DataObject
    {
        return $this->dataObjectFactory->create(
            [
                'data' => $this->process($this->template)
            ]
        );
    }

    /**
     * @param $template
     * @return mixed
     */
    protected function process($template)
    {
        foreach ($template as $key => $value) {
            switch (true) {
                case is_array($value):
                    $template[$key] = $this->process($value);
                    break;

                case is_string($value):
                    if ($this->startWith($value, '#') && $this->endsWith($value, '#')) {
                        $template[$key] = $this->variables[trim($value, '#')];
                    }
                    break;
            }
        }

        return $template;
    }

    /**
     * @param $haystack
     * @param $needle
     * @return bool
     */
    protected function startWith($haystack, $needle): bool
    {
        return $haystack[0] === $needle[0] && strncmp($haystack, $needle, \strlen($needle)) === 0;
    }

    /**
     * @param $haystack
     * @param $needle
     * @return bool
     */
    protected function endsWith($haystack, $needle): bool
    {
        return $needle === '' || substr_compare($haystack, $needle, -\strlen($needle)) === 0;
    }

    /**
     * @inheritDoc
     */
    public function setVariable(string $name, $value): TemplateInterface
    {
        $this->variables[$name] = $value;
        return $this;
    }
}
