<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// Created on Aug 26, 2011 by Damiano Venturin @ Squadra Informatica

class Rest_Client extends CI_Controller {
	public function __construct() 
	{
		parent::__construct();
		
		// Load the configuration file
		$this->load->config('rest');
		
		// Load the rest client
		$this->load->spark('restclient/2.0.0');		
		$this->rest->initialize(array('server' => $this->config->item('rest_server')));
		//$this->rest->initialize(array('server' => 'http://localhost/codeigniter-rest-example/index.php/rest_server/'));
	}
	
	public function index()
	{
		$data['methods_list'] = $this->displayAPI();
		$this->load->view('restDoc',$data);				
	}
	
	/**
	 * 
	 * Produces a human readable list of methods available on the server side
	 */
	public function displayAPI()
	{
		//get methods list
        $methods_html = '';
        $methods = (array) $this->rest->get('API/format/json');
        
        //show the docstring for the method
        if(count($methods['functions'])>0)
        {
        	foreach ( $methods['functions'] as  $method) {	    
				if(empty($method->docstring))
				{
					$methods_html .= '<dt>'.$method->function.'</dt><dd>No description available</dd>';
				} else {
					$methods_html .= '<dt>'.$method->function.'</dt><dd>'.$method->docstring.'</dd>';
				}
        	}	
        	$methods_html .= '</dl>';
        }
        	
//		echo '<pre>';
//		print_r($methods);
//		echo '</pre>';         

       	return $methods_html;				
	}		

	/**
	 * 
	 * Access API "users" using GET through Phil's rest client
	 */
	public function getUsers()
	{
		echo '<pre>';
		print_r($this->rest->get('users/format/json'));
		echo '</pre>';
	}
	
	/**
	 * 
	 * Access API "users" using GET through json_decode
	 */
	public function getUsersJson()
	{
		echo '<pre>';
		print_r(json_decode(file_get_contents($this->config->item('rest_server').'users/format/json')));
		echo '</pre>';		
	}
	
	/**
	 * 
	 * Access API "user" using GET through Phil's rest client
	 */
	public function getUser()
	{
		echo '<pre>';
		print_r($this->rest->get('user/id/1/format/json'));
		echo '</pre>';
	}
	
	/**
	 * 
	 * Access API "user" using DELETE through Phil's rest client
	 */
	public function delUser()
	{
		echo '<pre>';
		print_r($this->rest->delete('user/id/2/format/json'));
		echo '</pre>';
	}

	/**
	 * 
	 * Access API "helloWorld" using GET through Phil's rest client
	 */
	public function helloWorld()
	{
		echo '<pre>';
		print_r($this->rest->get('helloWorld/format/json'));
		echo '</pre>';
	}

	/**
	 * 
	 * Access API "contacts" using GET through Phil's rest client
	 */	
	public function getContacts()
	{
		echo '<pre>';
		print_r($this->rest->get('contacts/format/json'));
		echo '</pre>';		
	}	
	
	/**
	 * 
	 * Access API "API" using GET through Phil's rest client
	 */		
	public function getApi()
	{
		echo '<pre>';
		print_r($this->rest->get('API/format/json'));
		echo '</pre>';		
	}		
}

/* End of rc.php */