<?php
if (!defined('PICONTROL')) exit();

(include_once LIBRARY_PATH.'main/main.function.php')		or die('Error: 0x0000');
(include_once LIBRARY_PATH.'plugin/plugin.function.php')	or die('Error: 0x0001');

initPluginConstants();
(include_once PLUGIN_PATH.'resources/library/main/main.function.php') or die('Error: 9x0001');

if (isset($_POST['data']))
{
	$fritzboxAddress = getPluginConfig('main:address', 'http://fritz.box');
	$fritzboxVersion = getPluginConfig('main:version', '5');
	$fritzboxUnit = getPluginConfig('main:unit', 'mbit');
	
	$connectionFritzbox = checkConnectionToFritzbox($fritzboxAddress, $fritzboxVersion);
	
	if ($connectionFritzbox == true)
	{
		
		$currentBandwidth = getCurrentBandwidth($fritzboxAddress, $fritzboxVersion);
		$maxBandwidth = getMaxBandwidth($fritzboxAddress, $fritzboxVersion);
		
		$datas = explode(';', $_POST['data']);
		
		foreach ($datas as $data)
		{
			switch ($data)
			{
				case 'connection':
					$connectionStatus = getConnectionStatus($fritzboxAddress, $fritzboxVersion);
					$api->addData('connection', _t($connectionStatus['status']));
						break;
				case 'uptime':
					$connectionStatus = getConnectionStatus($fritzboxAddress, $fritzboxVersion);
					$api->addData('uptime', formatTime(time() - $connectionStatus['uptime']));
						break;
				case 'publicIP':
					$api->addData('publicIP', getPublicIP($fritzboxAddress, $fritzboxVersion));
						break;
				case 'totalSent':
					$traffic = getNetworkTraffic($fritzboxAddress, $fritzboxVersion);
					$api->addData('totalSent', sizeUnit($traffic['sent']));
						break;
				case 'totalReceived':
					$traffic = getNetworkTraffic($fritzboxAddress, $fritzboxVersion);
					$api->addData('totalReceived', sizeUnit($traffic['received']));
						break;
				case 'bandwidthDown':
					$currentBandwidth = getCurrentBandwidth($fritzboxAddress, $fritzboxVersion);
					$maxBandwidth = getMaxBandwidth($fritzboxAddress, $fritzboxVersion);
					
					$api->addData('current', convertToUnit($currentBandwidth['down'], $fritzboxUnit, 'byte'));
					$api->addData('max', convertToUnit($maxBandwidth['down'], $fritzboxUnit));
					$api->addData('percentage', getPercentageFromBandwidth($currentBandwidth['down'], $maxBandwidth['down']).'%');
						break;
				case 'bandwidthUp':
					$currentBandwidth = getCurrentBandwidth($fritzboxAddress, $fritzboxVersion);
					$maxBandwidth = getMaxBandwidth($fritzboxAddress, $fritzboxVersion);
					
					$api->addData('current', convertToUnit($currentBandwidth['up'], $fritzboxUnit, 'byte'));
					$api->addData('max', convertToUnit($maxBandwidth['up'], $fritzboxUnit));
					$api->addData('percentage', getPercentageFromBandwidth($currentBandwidth['up'], $maxBandwidth['up']).'%');
						break;
				default:
					$api->setError('error', 'Data for "'.$data.'" are not available.');
			}
		}
	}
	else
		$api->setError('error', 'No connection.');
}
else
	$api->setError('error', 'No data set.');
?>