<?php

namespace App\Tests;

use App\Tests\Stub\Smarty\SmartyModuleResource;
use PrestaShop\PrestaShop\Adapter\LegacyContext;

class SmartyFactory
{
    private LegacyContext $legacyContext;

    private string $projectDirectory;

    public function __construct(
        LegacyContext $legacyContext,
        string $projectDirectory
    ) {
        $this->legacyContext = $legacyContext;
        $this->projectDirectory = $projectDirectory;
    }

    /**
     * @param array<string> $params
     *
     * @return false|string
     */
    public function smartyTranslate($params)
    {
        if (
            isset($params['s']) && is_string($params['s'])
            && isset($params['d']) && is_string($params['d'])) {
            return $params['s'];
        }

        return \strval(\json_encode($params));
    }

    public function create(): \Smarty
    {
        $context = $this->legacyContext->getContext();

        \assert(null !== $context);

        $smarty = new \Smarty();
        $smarty->setCompileDir(_PS_CACHE_DIR_ . 'smarty/compile');
        $smarty->setCacheDir(_PS_CACHE_DIR_ . 'smarty/cache');
        $smarty->use_sub_dirs = true;
        $smarty->setConfigDir(_PS_SMARTY_DIR_ . 'configs');
        $smarty->caching = \Smarty::CACHING_OFF;
        $smarty->setTemplateDir($this->projectDirectory . '/tests/Stub/templates');
        $smarty->force_compile = true;
        $smarty->registerPlugin('function', 'l', [$this, 'smartyTranslate']);
        $smarty->registerResource(
            'module',
            new SmartyModuleResource($this->projectDirectory)
        );
        $smarty->assign([
            'link' => $context->link,
        ]);

        return $smarty;
    }
}
