<?php
/**
 * @license    http://www.cecill.info/licences/Licence_CeCILL-B_V1-fr.html
 * @author     Francois Merciol <dokuplugin@merciol.fr>
 *
 * Plugin Schedule: manage events per wiki @groups
 */

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

require_once (realpath (__DIR__.'/..').'/scheduleInseeCities.php');

// ============================================================
class syntax_plugin_schedule_display extends DokuWiki_Syntax_Plugin {
 
    // ============================================================
    function getInfo() {
        return confToHash (__DIR__.'/../INFO.txt');
    }
    function getType () { return 'substition'; }
    function getPType () { return 'block'; }
    function getSort () { return 299; }
    function connectTo ($mode) {
        $this->Lexer->addEntryPattern ('<schedule[^>]*>', $mode, 'plugin_schedule_display');
    }
    function postConnect () {
        $this->Lexer->addExitPattern ('</schedule>', 'plugin_schedule_display');
    }

    // ============================================================
    function handle ($match, $state, $pos, Doku_Handler $handler) {
        switch ($state) {
        case DOKU_LEXER_ENTER:
            return array ($state, trim (substr ($match, 8, -1))); // "<schedule" => 8 ">" => 1
        case DOKU_LEXER_UNMATCHED:
            return array ($state, $match);
        case DOKU_LEXER_EXIT:
            return array ($state, '');
        }
        return false;
    }

    // ============================================================
    function render ($mode, Doku_Renderer $renderer, $indata) {
        if (empty($indata))
            return false;
        if ($mode != 'xhtml')
            return false;
        list ($instr, $data) = $indata;
        switch ($instr) {
            
        case DOKU_LEXER_ENTER :
            $args = strtolower (" ".$data." ");
            $mapId = "scheduleMapPOI";
            $width = "";
            $height = "";
            if (preg_match_all ('/("[^"]*")* id="(?<id>[0-9a-zA-Z_]+)" ("[^"]*")*/', $args, $dumy) > 0)
                for ($i = 0; $i < count ($dumy['id']); $i++)
                    $mapId = $dumy ['id'][$i];
            if (preg_match_all ('/.* width=(?<width>[0-9]+) .*/', $args, $dumy) > 0)
                for ($i = 0; $i < count ($dumy['width']); $i++)
                    $width=' width="'.$dumy ['width'][$i].'"';
            if (preg_match_all ('/.* height=(?<height>[0-9]+) .*/', $args, $dumy) > 0)
                for ($i = 0; $i < count ($dumy['height']); $i++)
                    $height=' height="'.$dumy ['height'][$i].'"';
            $renderer->doc .=
                           '<div class="wrap_left plugin_wrap">'.NL.
                           ' <div class="schedulePOI scheduleScaledMap">'.NL;
            if ($this->getConf ('useMap')) {
                if (!is_dir (realpath (__DIR__.'/../../ol3')))
                    $renderer->doc .= '<p><a href="http://www.dokuwiki.org/plugin:ol3">ol3 plugin</a> not installed (see <a href="http://www.dokuwiki.org/plugin:schedule">doc</a>)</p>';
                $renderer->doc .= '  <div id="'.$mapId.'" class="scheduleMap scheduleMapDisplay"'.$width.$height.'></div>'.NL;
            }
            break;

        case DOKU_LEXER_UNMATCHED :
            $data = trim ($data);
            $address ="";
            if ($this->getConf ('useMap'))
                $renderer->doc .= '<span class="wrap_tip wrap_center wrap_centeralign">'.$this->getLang ('reactiveMap').'</span>'.NL;
            $renderer->doc .= '  <ul style="display:none;" class="poiLatLon">'.NL;

            global $scheduleInseeCities;
            if (! empty ($data))
                foreach (explode ("\n",  preg_replace ('%~[eE][nN][dD]~%', "\n", $data)) as $line) {
                    $line = trim (preg_replace ("/#.*$/", "", $line));
                    if (!$line)
                        continue;
                    $line = preg_replace ("#\s+\|#", "|", $line);
                    $line = preg_replace ("#\|\s+#", "|", $line);
                    $line = trim ($line,'|');
                    list ($insee, $lat, $lon, $addr, $occ) = explode ("|", $line);
                    // XXX vérif des formats (nombres, ...)
                    if (!$insee || !$lon) {
                        if ($insee && $lat)
                            $renderer->doc .= '   <li lat="'.$insee.'" lon="'.$lat.'">56000</li>'.NL; // XXX position par defaut
                        continue;
                    }
                    if ($insee && $lat && $lon) {
                        $iter=$occ?$occ:1;
                        for ($i = 1; $i <= $iter; $i++)
                            $renderer->doc .= '   <li lat="'.$lat.'" lon="'.$lon.'">'.$insee.'</li>'.NL;
                    }
                    $addrHtml =
                              ($addr ?
                               preg_replace ('%\\\\\\\\%', "<br/>", preg_replace ('%~[bB][rR]~%', "<br/>", $addr)) :
                               '<span class="wrap_round wrap_todo">'.$this->lang ('toComplet').'</span><br/>').' '.
                              // XXX all insee ???
                              (isset ($scheduleInseeCities[$insee]) ? $scheduleInseeCities[$insee][0] : $insee).'<br/>'.
                              (($addr && $lat && $lon) ? 
                               '<span style="font-size:50%; background-color:#DDD;">(Lat. : '.$lat.' Long. : '.$lon.')</span>' :
                               '');
                    $address .=
                             '<div class="scheduleAddresse wrap_left plugin_wrap" location="('.$lat.'|'.$lon.')">'.NL.
                             ' <p onMouseOver="javascript:scheduleHighlightLocation (\'('.$lat.'|'.$lon.')\')" onMouseOut="javascript:scheduleHighlightLocation (null)">'.$addrHtml.' </p>'.NL.
                             '</div>'.NL;
                }
            $renderer->doc .=
                           '  </ul>'.NL.
                           ' </div>'.NL.
                           '</div>'.NL.
                           $address.
                           '<div class="wrap_clear plugin_wrap"></div>'.NL;
            break;
        case DOKU_LEXER_EXIT :
            break;
        }
        return true;
    }

    // ============================================================
}