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

(include_once LIBRARY_PATH.'statistic/statistic.class.php')				or die('Error: 9x0001');
(include_once PLUGIN_PATH.'resources/library/main/main.function.php')	or die('Error: 9x0002');

$fritzboxAddress = getPluginConfig('main:address', 'http://fritz.box');
$fritzboxVersion = getPluginConfig('main:version', '5');
$fritzboxUnit = getPluginConfig('main:unit', 'mbit');

$connectionFritzbox = checkConnectionToFritzbox($fritzboxAddress, $fritzboxVersion);

$tpl->assign('address', $fritzboxAddress);
$tpl->assign('connectionFritzbox', $connectionFritzbox);

if ($connectionFritzbox == true)
{
	$connectionStatus = getConnectionStatus($fritzboxAddress, $fritzboxVersion);
	$traffic = getNetworkTraffic($fritzboxAddress, $fritzboxVersion);
	$currentBandwidth = getCurrentBandwidth($fritzboxAddress, $fritzboxVersion);
	$maxBandwidth = getMaxBandwidth($fritzboxAddress, $fritzboxVersion);
	
	$statistics = array();
	
	$controller = new StatisticController($tpl);
	$controller->loadStatistics('plugin/');
	
	if ($controller->checkStatistic('plugin/fritzbox.traffic-download') === true)
	{
		$builder = new StatisticBuilder();
		$builder->loadFromFile('plugin/fritzbox.traffic-download', 'fritzbox');
		$statistics[] = array('array' => $builder->getArray(), 'json' => $builder->getJSON());
	}
	
	if ($controller->checkStatistic('plugin/fritzbox.traffic-upload') === true)
	{
		$builder = new StatisticBuilder();
		$builder->loadFromFile('plugin/fritzbox.traffic-upload', 'fritzbox');
		$statistics[] = array('array' => $builder->getArray(), 'json' => $builder->getJSON());
	}
	
	$tpl->assign('model', getModelName($fritzboxAddress, $fritzboxVersion));
	$tpl->assign('connection', _t($connectionStatus['status']));
	$tpl->assign('uptime', formatTime(time() - $connectionStatus['uptime']));
	$tpl->assign('publicIP', getPublicIP($fritzboxAddress, $fritzboxVersion));
	$tpl->assign('totalSent', $traffic['sent']);
	$tpl->assign('totalReceived', $traffic['received']);
	$tpl->assign('currentBandwidthUp', convertToUnit($currentBandwidth['up'], $fritzboxUnit, 'byte'));
	$tpl->assign('currentBandwidthDown', convertToUnit($currentBandwidth['down'], $fritzboxUnit, 'byte'));
	$tpl->assign('maxBandwidthUp', convertToUnit($maxBandwidth['up'], $fritzboxUnit));
	$tpl->assign('maxBandwidthDown', convertToUnit($maxBandwidth['down'], $fritzboxUnit));
	$tpl->assign('percentageBandwidthUp', getPercentageFromBandwidth($currentBandwidth['up'], $maxBandwidth['up']));
	$tpl->assign('percentageBandwidthDown', getPercentageFromBandwidth($currentBandwidth['down'], $maxBandwidth['down']));
	$tpl->assign('statistics', $statistics);
}

$tpl->draw('index');
?>