<?php

/**
 * Class Smarty_Compiler_Webpack.
 *
 * Examples:
 *    {webpack file="icons.css"}   =>  "Vygeneruje absolutní cesku k souboru z manifest.json"
 */
class Smarty_Compiler_Webpack extends Smarty_Internal_CompileBase
{
    public $optional_attributes = ['_any'];

    public string $manifestLocation = __DIR__.'../../../../shop/web/build/manifest.json';
    public string $prefixPath = 'web/build/';

    /**
     * Triggruje error když během buildu dojde k chybě.
     */
    private function triggerError(string $title): void
    {
        trigger_error($title, E_USER_ERROR);
    }

    /**
     * @param $compiler Smarty_Internal_SmartyTemplateCompiler
     *
     * @return string
     */
    public function compile($args, $compiler)
    {
        $_args = $this->getAttributes($compiler, $args);
        $manifest = $this->parseManifest();
        if ($manifest === null) {
            $this->triggerError("Manifest.json file does not exists in location {$this->manifestLocation}");
        }

        $file = $_args['file'] ?? null;
        if ($file === null) {
            $this->triggerError("Parameter file in macro {webpack} is required. \n For example: {webpack file='example.css'}");
        }

        $file = str_replace(["'", '"'], '', $file);

        $text = $manifest[$this->prefixPath.$file] ?? null;
        if ($text === null) {
            $keys = array_map(fn ($v) => substr($v, strlen($this->prefixPath)), array_keys($manifest));
            $this->triggerError("File: {$text} does not exists. Compiler counts with default prefix 'web/build/'. Select valid one: \n".implode("\n", $keys));
        }

        return $text;
    }

    public function parseManifest(): ?array
    {
        $file = file_get_contents($this->manifestLocation);

        return $file === false ? null : json_decode($file, true);
    }
}
