<?php
/**
 * DokuWiki Plugin whoisinyourhackspace (Syntax Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Tim Schumacher <tim.daniel.schumacher@gmail.com>
 */

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

if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');

require_once DOKU_PLUGIN.'syntax.php';

class syntax_plugin_whoisinyourhackspace extends DokuWiki_Syntax_Plugin {

    public function getType() {
        return 'substition';
    }

    public function getPType() {
        return 'block';
    }

    public function getSort() {
        return 0;
    }

    public function connectTo($mode) {
      $this->Lexer->addSpecialPattern("(?:\[wiyh '.*?'\]|\[wiyh\])", $mode,'plugin_whoisinyourhackspace');
    }

    public function handle($match, $state, $pos, Doku_Handler $handler)
    {
      if (DOKU_LEXER_SPECIAL !== $state) {
        return [];
      }

      $matches = [];

      if (false !== preg_match("/wiyh '(.*?)'/", $match, $matches)) {
        return [$state, $match, $matches[1] ?? null];
      }

      return [$state, $match];
    }

    public function render($format, Doku_Renderer $renderer, $data) {
      global $conf;

      [$state, $match, $url] = $data;

      if($format != 'xhtml') return false;

      $api_path = $url ?: $this->getConf('api_path');

      if (empty ($api_path)) {
        $renderer->doc .= "<div>{$this->getLang('wiyh_no_api_path')}</div>";

        return true;
      }

      if (false === $file = file_get_contents($api_path)) {
        $renderer->doc .= "<div>{$this->getLang('wiyh_fetch_error')}</div>";

        return true;
      }

      $api = json_decode($file);

      $content = '';
      $content .= '<div class="hackerspace-room-state">';
      $content .= "<h3>" . $this->getLang('wiyh_heading') . "</h3>";

      if ($api->state->open) {
        $content .= $api->state->icon->open ? "<img class=\"icon\" src=\"{$api->state->icon->open}\" alt=\"{$api->space} ist besetzt.\" title=\"{$api->space} ist besetzt.\" />" : '';
        $content .= "<p class=\"text\">{$api->space} " . $this->getLang('wiyh_open') . "</p>";
      } else {
        $content .= $api->state->icon->open ? "<img class=\"icon\" src=\"{$api->state->icon->closed}\" alt=\"{$api->space} ist geschlossen.\" title=\"{$api->space} ist geschlossen.\" />" : '';
        $content .= "<p class=\"text\">{$api->space} " . $this->getLang('wiyh_closed') . "</p>";
      }

      $date = new DateTime();
      $date->setTimeStamp($api->state->lastchange);
      $content .= "<p class=\"text\"> seit " . $date->format('d.m.Y H:i') . " Uhr</p>";

      $content .= '<hr />';
      $content .= '</div>';

      $renderer->doc .= $content;

      return true;
  }
}

// vim:ts=4:sw=4:et: