<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Template;

use idoit\Module\SyneticsFlows\Automation\Automation;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;
use idoit\Module\SyneticsFlows\Template\TemplateVariables\TemplateVariables;
use Twig\Environment;
use Twig\Loader\ArrayLoader;

class TemplateFactory
{
    public function prepareVariables(?Invocation $invocation, ?Automation $automation): TemplateVariables
    {
        return new TemplateVariables($invocation);
    }

    public function forInvocation(Invocation $invocation, Automation $automation): Template
    {
        return $this->getService($this->prepareVariables($invocation, $automation));
    }

    public function getService(TemplateVariables $variables): Template
    {
        $twig = new Environment(new ArrayLoader(), [
            'autoescape' => false
        ]);
        $twig->addExtension(new TemplateExtension());
        $vars = $variables->getVariables();
        foreach ($vars as $name => $value) {
            $twig->addGlobal($name, $value);
        }
        return new Template($twig);
    }
}