<?php
namespace Engine\Theme\JSLoader\Export;

/**
 * Abstract class used to implement exporters used by JSLoader and/or from the "old" loadjs.php script to export various internal settings & LANG vars into the final JS file
 * @author Lucian Sirbu
 */
abstract class AbstractExport
{
    /**
	 * Internal data
	 */
    protected array $data = [];

    public function __construct()
    {
    }

    /**
	 * Gather needed data and store in $this->data
     * @return $this
	 */
    abstract public function gather(): static;

    /**
	 * Return the data as JSON
     * @return string
	 */
    abstract public function asJSON(): string;

    /**
     * Recalculate the final file hash, to be sure the final file hash is unique
     * @param array $hash
     * @return array
     */
    public function rehashOutputFilename(array $hash): array
    {
        return $hash;
    }

    /**
     * Export an array in a JSON object(overwrites any pre-defined object with the same name in the browser-DOM)
     * @param string $jsVar
     * @param array $variables
     * @param string $pre
     * @return string
     */
    protected function exportBulkVariables(string $jsVar, array $variables, string $pre = ""): string
    {
        return sprintf("{$pre}{$jsVar} = %s;", json_encode($variables));
    }

    /**
     * Export and array one member at a time. Goes recursivelly through the input data
     * @param string $jsVar
     * @param array $variables
     * @param string $pre
     * @return string
     */
    protected function exportIndividualVariables(string $jsVar, array $variables, string $pre = ""): string
    {
        $output = [];
        foreach ($variables as $jsKey => $values) {
            if (is_array($values)) {
                // go deeper
                $output[] = $this->exportIndividualVariables("['{$jsKey}']", $values, $pre . $jsVar);
            }
            else {
                // export this value
                $output[] = sprintf("{$pre}{$jsVar}['{$jsKey}'] = %s;", json_encode($values));
            }
        }
        return implode("\n", $output);
    }

    /**
     * Export and merge with pre-existing variables. On-line with the "old" loadjs.php script
     * @param string $jsVar
     * @param array $variables
     * @param string $pre
     * @return string
     */
    protected function exportBulkVariablesAndMerge(string $jsVar, array $variables, string $pre = ""): string
    {
        // Merge into an existing JS object (or create it if missing) instead of overwriting it
        // Resulting JS example: Calendar._TT = Object.assign(Calendar._TT || {}, { ... });
        return sprintf("{$pre}%s = Object.assign({$pre}%s || {}, %s);", $jsVar, $jsVar, json_encode($variables));
    }

}
