<?php
/**
 * DokuWiki Plugin jsontable (Helper Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Janez Paternoster <janez.paternoster@siol.net>
 */

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

class helper_plugin_jsontable extends helper_plugin_json {

    /**
     * Handle extension to syntax_plugin_json_define
     *
     * @param array $data Reference to $data, which can be further manipulated
     */
    public function handle(&$data) {
        $json_o = $this->loadHelper('json');

        //options for the handsontable
        $options = $data['keys']['options'] ?? null;
        $options = is_string($options) ? $options : '{}';

        $data['options'] = $options;
        //replace %$ ... % snippets with data - prepare
        $data['options_extractors'] = $json_o->extractors_handle($options);

        //If 'save' attribute is set to 'all', then complete json object
        //from handsontable will be saved into <json> element.
        //Othervise only difference between original data and inline
        //data will be saved (default).
        $save = $data['keys']['save'] ?? null;
        if(is_string($save) && strtolower($save) === 'all') {
            $data['saveall'] = 'true';
        }
        else {
            $data['saveall'] = 'false';
            $data['display'] .= ',orig-hidden';
        }

        //make sure, necessary json data will be there
        $data['display'] .= ',inl-hidden,comb-hidden';
    }


    /**
     * Render extension to syntax_plugin_json_define
     *
     * For parameters see render::syntax_plugin_json_define
     *
     * @param array $data from handler
     * @param array $class definitions for parent div
     * @param array $data_attr html data attributes
     * @param array $tabs definitions for jQuery UI tabs widget
     * @param array $body definitions for jQuery UI tabs widget
     * @param array $log for reporting errors
     * @param array $tab_no must incerment for each tab
     * @param array $tab_number for id attribute
     */
    public function render(Doku_Renderer $renderer, &$data, &$class, &$data_attr, &$tabs, &$body, &$log, &$tab_no, $tab_number) {
        //replace %$ ... % snippets with data
        if(count($data['options_extractors']) > 0) {
            $json_o = $this->loadHelper('json');
            $options = $json_o->extractors_replace($data['options'], $data['options_extractors']);
        }
        else {
            $options = $data['options'];
        }

        $data_attr['active'] = $tab_no++;   //make this tab active
        $data_attr['options'] = htmlspecialchars($options);
        $data_attr['saveall'] = $data['saveall'];

        $class[] = 'jsontable-plugin';
        $tabs[] = '<li><a href="#json-tab-'.$tab_number.'-table">Table</a></li>';
        $body[] =      '<div id="json-tab-'.$tab_number.'-table"><div class="json-table"></div></div>';
    }
}
