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

if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_tablemath extends DokuWiki_Syntax_Plugin {

    /**
     * return some info
     */
    function getInfo() {
        return array(
                'author' => 'James GuanFeng Lin',
                'email'  => 'guanfenglin@gmail.com',
                'date'   => '2009-08-24',
                'name'   => 'Table Math Plugin',
                'desc'   => 'Enables calculated columns in built in table syntax',
                'url'    => 'https://www.dokuwiki.org/plugin:tablemath',
                );
    }

    function getType() { return 'substition'; }
    function getSort() { return 1213; }

    /**
     * Connect pattern to lexer
     */
    function connectTo($mode) {
        $this->Lexer->addSpecialPattern("~~=[a-zA-Z0-9_]*\([0-9,:]*\)~~", $mode, 'plugin_tablemath');
    }

    /**
     * Handle the match
     */
    function handle($match, $state, $pos, &$handler) {
        global $ID, $ACT, $INFO;
        $match = str_replace('~~', '', $match);
        $match = str_replace('=', '', $match);
        $tmp = explode('(', $match);
        if (count($tmp)>1)
        {
                $tmp[1] = str_replace(')', '', $tmp[1]);
                return array('method'=>$tmp[0],'set'=>$tmp[1], 'divid'=>'tm'.rand());
        }
        return array();
    }

    function render($mode, &$renderer, $data) {
        global $INFO, $ID, $conf;
        if($mode == 'xhtml'){
                  // get discussion meta file name
          $renderer->doc .= '<html><div id="'.$data['divid'].'"><script type="text/javascript" defer="defer">tablemath("'.$data['divid'].'","'.$data['method'].'","'.$data['set'].'");</script></div></html>';
          return true;
        }
        return false;
    }

}