<?php
/*
 * XXX
 */
 
if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
require_once(DOKU_PLUGIN.'calendoku/helper.php');

// start end duration contact summary url uid created last-modified 
// sequence x-calendoku-version prodid tzname description organizer 
// location class
//
class syntax_plugin_calendoku_showtable extends DokuWiki_Syntax_Plugin {

    function getType()  { return 'substition'; }
    function getPType() { return 'block'; }
    function getSort()  { return 42; }
    function getAllowedTypes() {
        return array('formatting', 'substition', 'paragraphs', 'baseonly');
    }
    
    function connectTo($mode) {
        $this->Lexer->addSpecialPattern(
            '\{\{calendoku>.*?>\s*\}\}',
            $mode,
            'plugin_calendoku_showtable');
    }

    function handle($match, $state, $pos, &$handler) {
        $match = preg_replace('/^\{\{calendoku(.*)\}\}/', '\1', $match);

        /* Get the fields we want to show. */
        $tmpfields = array();
        if (preg_match('/(?<=>)\s*FIELDS=(.*?)(?=>)/', $match, $fieldsstr)) {
            $this->fields = preg_split('/(?<!\\\\) /', $fieldsstr[1]);
        } else {
            $this->fields = array('DTSTART', 'DTEND', 'SUMMARY', 'CONTACT', 'URL');
        }

        /* Get the formatted field descriptions. */
        $tmpfielddescs = array();
        if (preg_match('/(?<=>)\s*FIELDDESCS=(.*?)(?=>)/', $match, $fielddescsstr)) {
            $this->fielddescs = preg_split('/(?<!\\\\) /', $fielddescsstr[1]);
        } else {
            $this->fielddescs = $tmpfields;
        }

        /* Get the type of the calendar we want to show. */
        if (preg_match('/(?<=>)\s*TYPE=(.*?)(?=>)/', $match, $typestr)) {
            if (!strcmp($typestr[1], 'VTABLE'))
                $this->type = 'VTABLE';
            else
                $this->type = 'VTABLE';
        } else {
            $this->type = 'VTABLE';
        }

        /* Get the start date. */
        if (preg_match('/(?<=>)\s*START=(.*?)(?=>)/', $match, $startstr)) {
            if (!strcmp($startstr[1], 'CURRENT'))
                $startdate = guessDateTime(date('U'));
            else
                $startdate = guessDateTime($startstr[1]);
        } else {
            $startdate = guessDateTime('0');
        }

        /* Get the end date. */
        if (preg_match('/(?<=>)\s*END=(.*?)(?=>)/', $match, $endstr)) {
            if (!strcmp($endstr[1], 'CURRENT'))
                $enddate = guessDateTime(date('U'));
            else {
                $enddate = guessDateTime($endstr[1]);
            }
        } else {
            $enddate = guessDateTime('0');
        }

        /* Get the namespaces to be searched. */
        // XXX: Colon separation won't work for sub namespaces!
        if (!preg_match('/(?<=>)\s*NAMESPACE=(.*?)(?=>)/', $match, $namespacestr))
            return false;
        $namespaces = preg_split('/(?<!\\\\) /', $namespacestr[1]);

        /* Go through all namespaces and their pages. */
        $templates = preg_split('/\s/', $this->getConf('icaltemplates'));
        foreach ($namespaces as $namespace) {
            $namespace = preg_replace('/\\ /', ' ', $namespace);
            $data = ft_pageLookup($namespace, true, false);
            foreach($data as $pagename => $title) {
                if (strcmp(getNS($pagename), $namespace))
                    continue;

                $docontinue = false;
                foreach($templates as $template)
                    if (!strcmp($template, $pagename)) {
                        $docontinue = true;
                        break;
                    }
                if ($docontinue)
                    continue;

                $page = rawWiki($pagename);

                $object = new CalenDoku_CalendarObject($this, $page);
                if (count($object->components) > 0) {
                    foreach ($object->components as $component) {
                        if ($component->invalid)
                            continue;
                        if ($component->isWithinTime($startdate, $enddate)) {
                            if (isset($components[$component->dtstartint]))
                                array_push($components[$component->dtstartint], array($component, $pagename));
                            else
                                $components[$component->dtstartint] = array(array($component, $pagename));
                        }
                    }
                }
            }
        }


        /* Insert pages sorted. */
        ksort($components, SORT_NUMERIC);
        $this->startCalendar($pos, $handler);
        foreach ($components as $mcomponent) {
            foreach ($mcomponent as $component) {
                $this->addEntryCalendar($component[0], $component[1], $pos, $handler);
            }
        }
        $this->endCalendar($pos, $handler);
    }

    function startCalendar($pos, &$handler) {
        if (!strcmp($this->type, 'VTABLE')) {
            $handler->_addCall('table_open', array(), $pos);
            $handler->_addCall('tablerow_open', array(), $pos);
            foreach ($this->fielddescs as $fielddesc) {
                $handler->_addCall('tableheader_open', array(), $pos);
                reHandleText($fielddesc, $pos, $handler);
                $handler->_addCall('tableheader_close', array(), $pos);
            }
            $handler->_addCall('tablerow_close', array(), $pos);
        }
    }

    function endCalendar($pos, &$handler) {
        if (!strcmp($this->type, 'VTABLE'))
            $handler->_addCall('table_close', array(), $pos);
    }

    function addEntryCalendar($component, $pagename, $pos, &$handler) {
        $handler->_addCall('tablerow_open', array(), $pos);
        foreach ($this->fields as $field) {
            preg_match_all('/(@@.*?@@)/', $field, $matches);
            foreach ($matches[1] as $match) {
                $sfield = preg_replace('/@@(.*)@@/', '\1', $match);
                if (!strcmp($sfield, 'DOKUWIKILINK'))
                    $field = preg_replace('/'.$match.'/', $pagename, $field);
                else if (!strcmp($sfield, 'DOKUWIKIICAL'))
                    $field = preg_replace('/'.$match.'/', $pagename.'?do=ical', $field);
                else if (isset($component->renderfields[$sfield]))
                    $field = preg_replace('/'.$match.'/', $component->renderfields[$sfield], $field);
                else
                    $field = preg_replace('/'.$match.'/', '', $field);
            }
            $handler->_addCall('tablecell_open', array(), $pos);
            reHandleText($field, $pos, $handler);
            $handler->_addCall('tablecell_close', array(), $pos);
        }
        $handler->_addCall('tablerow_close', array(), $pos);
    }

    function render($mode, &$renderer, $data) {
        return true;
    }
}
//Setup VIM: ex: et ts=4 enc=utf-8 :
