<?php
set_include_path('/usr/share/Ice-3.4.2/php/lib');

// Connection string (so called 'stringified proxy')
$PROXY_STRING = 'Meta:tcp -h 127.0.0.1 -p 6502';

// Make sure $ICE_PATH/php is on your include path
require('Ice.php');
// Code generated by calling 'slice2php Murmur.ice'
require('/opt/murmur/Murmur.php');

// Get request parameters
$callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : null;

// Set response headers
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: text/javascript; charset=utf-8');

// Initialize Ice
$communicator = Ice_initialize();
$base = $communicator->stringToProxy($PROXY_STRING);
$meta = $base->ice_checkedCast("::Murmur::Meta");

// Mapping function
function mapTree2Model($tree) {
    $channels = array();
    for ($i = 0; $i < count($tree->children); $i++) {
        $channels[] = mapTree2Model($tree->children[$i]);
    }
    $users = array();
    for ($i = 0; $i < count($tree->users); $i++) {
        $users[] = $tree->users[$i]->name;
    }
    return array(
        'name' => $tree->c->name,
        'channels' => $channels,
        'users' => $users
    );
}

// Prepare JSON
$tree = $meta->getServer(1)->getTree();
$json = json_encode(mapTree2Model($tree));

// Render response
if (!empty($callback)) {
    echo $callback . '(' . $json . ');';
} else {
    echo $json;
}

