<?php
set_time_limit(60);
ob_start();
require_once("../restricted/tahoma_EG.php");
//67ebd23e3a61763386d9
function getSSLPage($url, $tahoma_token)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "Authorization: Bearer ".$tahoma_token));
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSLVERSION, 3);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	if (curl_errno($ch)) {
		$error_msg = curl_error($ch);
		//print $error_msg;
	}
	curl_close($ch);
	return $result;
}

function postSSLPage($url, $body, $tahoma_token)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "Authorization: Bearer ".$tahoma_token));
	curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_SSLVERSION, 3);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	if (curl_errno($ch)) {
		$error_msg = curl_error($ch);
		//print $error_msg;
	}
	curl_close($ch);
	return $result;
}



function filter_devs($arr,$filter,$prefix=""){
	$ret = Array();
	$i = 0;
	foreach($arr as $key => $dev){
		$start = strpos(strtolower($dev["name"]),strtolower($filter));
		if($start !== false){
			$ret[$i]["name"] = $prefix.substr($dev["name"],strlen($filter));
			$ret[$i]["id"] = $key;
			$i++;
		}
	}
	return $ret;
}

function searchForDevice($device){
	$dev = false;
	$devices = json_decode(file_get_contents('../restricted/tahoma_devices.json'), true);
	if (strlen($device) < 3 && intval($device) >= 0 && intval($device) < sizeof($devices)) {
		$dev = $devices[intval($device)];
	} else if ($key = array_search($device, array_column($devices, "name"))) {
		$dev = $devices[$key];
	} else if ($key = array_search($device, array_column($devices, "id"))) {
		$dev = $devices[$key];
	} else {
		return false;
	}
	return $dev;
}

if ($_GET["action"] == "devlist") {
	$jalousien = array();
	$url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/setup/devices';
	$ret = getSSLPage($url,$tahoma_token);
	$devices = json_decode($ret, true);
	$i = 0;
	foreach ($devices as $device) {
		if ($device["controllableName"] == "io:ExteriorVenetianBlindIOComponent") {
			$jalousien[$i]["name"] = $device["label"];
			$jalousien[$i]["id"] = $device["deviceURL"];
			$i = $i + 1;
			echo $device["label"] . "(".$device["deviceURL"].")<br />";
		}
	}
	$file = fopen('../restricted/tahoma_devices.json', 'w');
	fwrite($file, json_encode($jalousien));
	fclose($file);
}elseif ($_GET["action"] == "pos" && isset($_GET["device"])) {
	$dev = searchForDevice($_GET["device"])["id"];
	$devices = json_decode(file_get_contents('../restricted/tahoma_devices.json'), true);
	$jalousien = array();
	$url = $url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/setup/devices/'.urlencode($dev)."/states";
	$ret = getSSLPage($url,$tahoma_token);
	$states = json_decode($ret, true);
	$out = "{";
	foreach ($states as $state){
		if ($state["name"] == "core:SlateOrientationState")
			$out .= "\"rotation\":".$state["value"].",";
		if ($state["name"] == "core:ClosureState")
			$out .= "\"position\":".$state["value"].",";
	}
	$out = substr($out,0,-1);
	$out .= "}";
	echo $out;
	header('Connection: close');
	header('Content-Length: '.ob_get_length());
	ob_end_flush();
	@ob_flush();
	flush();
	fastcgi_finish_request();
}elseif ($_GET["action"] == "moving" && isset($_GET["device"])) {
	$dev = searchForDevice($_GET["device"])["id"];
	$devices = json_decode(file_get_contents('../restricted/tahoma_devices.json'), true);
	$jalousien = array();
	$url = $url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/setup/devices/'.urlencode($dev)."/states/core:MovingState";
	$ret = getSSLPage($url,$tahoma_token);
	$moving = json_decode($ret, true);
	if($moving["value"])
		echo "true";
	else
		echo "false";
	header('Connection: close');
	header('Content-Length: '.ob_get_length());
	ob_end_flush();
	@ob_flush();
	flush();
	fastcgi_finish_request();
}elseif ($_GET["action"] == "move" && isset($_GET["pos"]) && isset($_GET["angle"]) && isset($_GET["device"])) {
	$angle = $_GET["angle"];
	$pos = $_GET["pos"];
	if ($pos < 0 || $pos > 100) {
		echo "Position out of Range";
		exit;
	}
	if ($angle < 0 || $angle > 100) {
		echo "Angle out of Range";
		exit;
	}
	$dev = searchForDevice($_GET["device"])["id"];
	if($dev == false){
		exit;
	}
	header('Connection: close');
	header('Content-Length: '.ob_get_length());
	$url = $url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/setup/devices/'.urlencode($dev)."/states/core:MovingState";
	$ret = json_decode(getSSLPage($url,$tahoma_token),true);
	
	$action = array();
	$action["label"] = "myAction";
	$action["actions"] = array();
	$action["actions"][0]["deviceURL"] = $dev;
	$action["actions"][0]["commands"] = array();
	if(!isset($ret["value"])){
		$ret = json_decode(getSSLPage($url,$tahoma_token),true);
	}

	if(!isset($ret["value"]) || $ret["value"] == false){
		$url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/exec/apply';
		echo "start";
		ob_end_flush();
		@ob_flush();
		flush();
		fastcgi_finish_request();
		$action["actions"][0]["commands"][0]["name"] = "setClosureAndOrientation";
		$action["actions"][0]["commands"][0]["parameters"][0] = intval($pos);
		$action["actions"][0]["commands"][0]["parameters"][1] = intval($angle);
		$res = json_decode(postSSLPage($url,json_encode($action),$tahoma_token));
		if(!isset($res["execId"])){
			sleep(1);
			$res = json_decode(postSSLPage($url,json_encode($action),$tahoma_token)); //2nd try
		}
	}elseif($ret["value"] == true){
		$url = 'https://gateway-'.$tahoma_PIN.':8443/enduser-mobile-web/1/enduserAPI/exec/apply';
		echo "stop";
		ob_end_flush();
		@ob_flush();
		flush();
		fastcgi_finish_request();
		$action["actions"][0]["commands"][0]["name"] = "stop";
		$res = json_decode(postSSLPage($url,json_encode($action),$tahoma_token));
		if(!isset($res["execId"])){
			sleep(1);
			$res = json_decode(postSSLPage($url,json_encode($action),$tahoma_token));	//2nd try
		}
	}
}




if ($_GET["action"] == "myactors") {
	if(isset($_GET["filter"])){
		$host = $_GET["filter"];
		$host = str_replace("-", "", strtolower($host));
	}else{
		$host = gethostbyaddr("192.168.179.32");
		$host = str_replace("-", "", strtolower(substr($host, 0, strpos($host, "."))));
	}
	$devices = json_decode(file_get_contents('../restricted/tahoma_devices.json'), true);
	switch ($host) {
		case "tmpegbad":
			echo json_encode(filter_devs($devices, "bad "));
			break;
		case "tmpegwozi":
			echo json_encode(filter_devs($devices, "wozi "));
			break;
		case "tmpegflorian":	//flori
			$ret = filter_devs($devices, "florian ","Flori ");
			$ret = array_merge($ret, filter_devs($devices, "magdalena ","Magdalena "));
			echo json_encode($ret);
			break;
		case "tmpegmagdalena":
			echo json_encode(filter_devs($devices, "magdalena "));
			break;
		case "tmpegschlafzimmer":
			echo json_encode(filter_devs($devices, "schlafzimmer "));
			break;
		default:
			$ret2=Array();
			//$ret2[0]["name"] = $host;
			//$ret2[0]["id"] = 99;
			$ret = filter_devs($devices, "");
			//$ret = array_merge($ret, $ret2);
			echo json_encode($ret);
			break;
	}
	header('Connection: close');
	header('Content-Length: '.ob_get_length());
	ob_end_flush();
	@ob_flush();
	flush();
	fastcgi_finish_request();


	//echo postSSLPage($url,json_encode($action));
}
