<?php


class CoreRESTfulBridge {



	public static function getProcesses() {

		return CoreRESTfulBridge::RESTfulCall("dbserver", "getprocesses", array(),"6858");
	}


	public static function dumpKeys() {
		return CoreRESTfulBridge::RESTfulCall("dbserver", "dump", array());
	}



	public static function triggerPhoneProvisioning($obj) {

		$name = get_class($obj);
		if ($name === false) {
			return false;
		}
			
		$module_data = false;
		if ($name == "Phones") {
			$module_data = array("phoneid" => $obj->id);
		} else if ($name == "User") {
			$module_data = array("userid" => $obj->id);
		}

		if ($module_data !== false) {
			CoreRESTfulBridge::RESTfulCall("provisioning", "trigger", $module_data);
		}
	}


	public static function sendFax($faxModel) {

		$name = get_class($faxModel);
		if ($name === false) {
			return false;
		}
			
		$module_data = false;
		if ($name == "Fax") {
			$module_data = array("faxfilecontent" => base64_encode($faxModel->faxfilecontent));
		} else {
			return false;
		}

		if ($module_data !== false) {
			return CoreRESTfulBridge::RESTfulCall("fax", "send", $module_data);
		}
		return false;
	}

	public static function getFaxData($faxModel) {

		$name = get_class($faxModel);
		if ($name === false) {
			return false;
		}
			
		$module_data = false;
		if ($name == "Fax") {
			//$module_data = array("faxfilecontent" => base64_encode($obj->faxfilecontent)); //FIXME: Base64encoding!
			$module_data = array("id" => $faxModel->id);
		} else {
			return false;
		}

		if ($module_data !== false) {
			return CoreRESTfulBridge::RESTfulCall("fax", "recv", $module_data);
		}
		return false;
	}


	private static function RESTfulCall($module, $action, $data, $port=6857) {
        return; // FIXME ! 
		$data = array("module" => $module, "action" => $action , "data" => $data);
		$data_string = json_encode($data);
		$databaseServer = Yii::app()->params['databaseServer'];
		$ch = curl_init('http://'.$databaseServer.':'.$port); //FIXME: get URL from settings or Cluster!
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Content-Type: application/json',
		'Content-Length: ' . strlen($data_string))
		);

		$data = curl_exec($ch);
			
		if ($data === false) {
			throw new CDbException("Could not connect to Database Server: ".$databaseServer.":".$port);
		}
			
		//echo "duration: ".$time." -> ".(microtime(true) ."                   ");
		return json_decode($data);

	}



}


?>