<?php

/*
Plugin Name: Knowledge Space
Description: This plugin adds a knowledge space to the website via a shortcode.
Version: 1.0
Author: Matthias Konitzny
*/

function ks_add_graph(): string
{
    $graph = '<script src="//unpkg.com/3d-force-graph"></script>';
    $three = '<script src="//unpkg.com/three"></script>';
    $renderer = '<script src="//unpkg.com/three/examples/js/renderers/CSS2DRenderer.js"></script>';
    $renderer2 = '<script src="//unpkg.com/three/examples/js/renderers/CSS3DRenderer.js"></script>';
    $div = '<div id="3d-graph"></div>';
    $plugin_dir = plugin_dir_url(__FILE__);
    //$dataset = $plugin_dir.'datasets/miserables.json';
    $variables = "<script> 
                  var plugin_path = '$plugin_dir';
                  </script>";
    $script_path1 = $plugin_dir.'display'.DIRECTORY_SEPARATOR.'infooverlay.js';
    $script_path2 = $plugin_dir.'display'.DIRECTORY_SEPARATOR.'linkoverlay.js';
    $script_path3 = $plugin_dir.'display'.DIRECTORY_SEPARATOR.'graph.js';

    $script1 = "<script src='$script_path1'></script>";
    $script2 = "<script src='$script_path2'></script>";
    $script3 = "<script src='$script_path3'></script>";


    return $three . $renderer .$renderer2 . $graph . $div . $variables . $script1 . $script2 .$script3;
}

function ks_add_editor(): string
{
    // Proper, secure script loading in the future
    // Reference https://stackoverflow.com/a/16823761/7376120
    wp_enqueue_script('jquery');

    $plugin_url = plugin_dir_url(__FILE__);

    $raw_html = file_get_contents(__DIR__.DIRECTORY_SEPARATOR."editor".DIRECTORY_SEPARATOR."editor.html");
    $ready_html = str_replace("%WWW%", $plugin_url, $raw_html);

    return $ready_html;
}

function kg_load_css() {
    $plugin_dir = plugin_dir_url(__FILE__);
    wp_enqueue_style('kg-style', $plugin_dir.'kg-style.css');
}

add_action('wp_enqueue_scripts', 'kg_load_css');
add_shortcode('knowledge-space', 'ks_add_graph');
add_shortcode('knowledge-space-editor', 'ks_add_editor');