<?php

use dokuwiki\Extension\SyntaxPlugin;

/**
 * DokuWiki Plugin networkgraph (Syntax Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author Feralheart <dokuwiki@feralheart.dev>
 */
class syntax_plugin_networkgraph_renderer extends SyntaxPlugin
{
    /** @inheritDoc */
    public function getType()
    {
        return 'substition';
    }

    /** @inheritDoc */
    public function getPType()
    {
        return 'normal';
    }

    /** @inheritDoc */
    public function getSort()
    {
        return 361;
    }

    /** @inheritDoc */
    public function connectTo($mode)
    {
        $this->Lexer->addSpecialPattern('~~NETWORKGRAPH(?:\|[a-zA-Z0-9\:\-\#\;\=]+)?~~', $mode, 'plugin_networkgraph_renderer');
    }

    /** @inheritDoc */
    public function handle($match, $state, $pos, Doku_Handler $handler)
    {
        $params = '';
        $cleanMatch = trim($match, '~');
        if (strpos($cleanMatch, '|') !== false) {
            $paramsString = substr($cleanMatch, strpos($cleanMatch, '|') + 1);

            if (strpos($paramsString, '=') !== false) {
                list($key, $value) = explode('=', $paramsString, 2);
                $key = trim($key);
                $value = trim($value);

                if ($key === 'colors') {
                    $params = $value;
                }
            } else {
                $params = $paramsString;
            }
        }

        $colorMap = $this->parseColorMap($params);

        return ['colors' => $colorMap];
    }

    /** @inheritDoc */
    public function render($mode, Doku_Renderer $renderer, $data)
    {
        if ($mode !== 'xhtml') {
            return false;
        }

        $colorMap       = $data['colors'] ?? [];
        $randomNumber   = rand(0, getrandmax());
        $graphId        = "networkgraph_" . $randomNumber;
        $file           = metaFN('networkgraph_data', '.json');
        $json           = file_exists($file) ? file_get_contents($file) : json_encode(['nodes' => [], 'links' => []]);
        $renderer->info['cache'] = false;
        $renderer->doc .= "<div id='" . $graphId . "' class='networkgraph' style='width:100%; height:600px; border:1px solid #ddd;'></div>";
        $renderer->doc .= "<script>
            (function() {
                const graph = " . $json . ";
                const colorMap = " . json_encode($colorMap) . ";
                renderGraph('" . $graphId . "', graph, colorMap);
            })();
        </script>";

        return true;
    }

    private function parseColorMap($param) {
        $colorMap = [];

        if (!$param) return $colorMap;

        $entries = explode(';', $param);

        foreach ($entries as $entry) {
            if (strpos($entry, '-') === false) continue;

            list($ns, $color) = explode('-', $entry, 2);

            $color = trim($color);

            if (preg_match('/^#?[0-9a-fA-F]{6}$/', $color)) {
                $color = ltrim($color, '#');
                $colorMap[trim($ns)] = '#' . strtolower($color);
            }
        }

        return $colorMap;
    }
}
