<?php

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

use dokuwiki\Extension\ActionPlugin;
use dokuwiki\Extension\EventHandler;
use dokuwiki\Extension\Event;
use dokuwiki\Logger;

/**
 * DokuWiki Plugin jstweak (Action Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author Volker Bürckel <volker@vrbdev.eu>
 */

class action_plugin_jstweak extends ActionPlugin
{
    const PLUGIN_PATH = DOKU_INC . 'lib/plugins/';
    const SCRIPT_NAME = 'script.js';
    
    /** @inheritDoc */
    public function register(EventHandler $controller)
    {
        $controller->register_hook('JS_SCRIPT_LIST', 'AFTER', $this, 'handleJsScriptList');
    }

    /**
     * Event handler for JS_SCRIPT_LIST
     * 
     * For any plugin's script.js found in the list, it checks for existence 
     * of a local override script.js in the subdirectory 
     *   plugins.script.local.js.d/<pluginName>/ 
     * of the conf directory.
     *
     * @see https://www.dokuwiki.org/devel:events:JS_SCRIPT_LIST
     * @param Event $event Event object, $event->data holds the list
     * @param mixed $param optional parameter passed when event was registered
     * @return void
     */
    public function handleJsScriptList(Event $event, $param)
    {
        // exit function if tweaking is switched off
        if (!$this->getConf('active')) {
            Logger::debug("jstweak: tweaking is switched off in config");
            return;
        }
        $overridePath = DOKU_CONF . $this->getConf('local_script_dir');
        $pluginPathLen = strlen(self::PLUGIN_PATH);
        $scriptNameLen = strlen(self::SCRIPT_NAME);

        if (!str_ends_with($overridePath, '/')) {
            $overridePath .= '/';
        }
        foreach ($event->data as $key => $entry) {
            // if we have a plugin's script.js file...
            if (str_starts_with($entry, self::PLUGIN_PATH) 
                && str_ends_with($entry, self::SCRIPT_NAME)) {
                // ... extract the plugin's name, ...
                $pluginName = substr(
                    $entry,
                    $pluginPathLen,
                    strlen($entry) - $pluginPathLen - $scriptNameLen - 1
                );
                // ... check if there's a local replacement file ...
                $newEntry = $overridePath . $pluginName . '/' . self::SCRIPT_NAME;
                if (file_exists($newEntry)) {
                    // ... and if yes: change the script list.
                    $event->data[$key] = $newEntry;
                    Logger::debug("jstweak: new script.js for plugin $pluginName -> $newEntry");
                }
            }
        }
    }
}
