/**
 * Returns the average CPU over the past Nx
 * N = number of units
 * x = unit (minutes, hours, days, years, etc)
 *
 * @example average_cpu("-5 minutes")
 * @param String $ago
 * @return Float
 **/
function averages($deployment_id)
{
    global $table;
    $ago = str_to_ticks("-5 minutes");
    $one_min = str_to_ticks("-1 minute");
    $info = '';
    try {
        $filter = "DeploymentId eq '{$deployment_id}' and  Role eq 'WebRole' and PartitionKey gt '0{$ago}'";
        //$filter = "Role eq 'WebRole'";
        //$filter = '';
        //echo "\nFilter: $filter";
        $info = $table->retrieveEntities('WADPerformanceCountersTable', $filter);
    } catch (Exception $e) {
        echo "\nAn error ocurred while retrieving the entities";
    }
    $sum = 0;
    $i = 0;
    $x = 0;
    $total_cons = 0;
    $role_cons = array();
    $rx = array();
    //var_dump($info);
    foreach ($info as $c) {
        //echo "\nChecking " . $c->CounterName . " with " . $c->CounterValue;
        if ($c->CounterName == '\\Processor(_Total)\\% Processor Time') {
            //echo "\nChecking " . $c->CounterName . " with " . $c->CounterValue;
            $sum += $c->CounterValue;
            $i++;
        }
        if ($c->CounterName == '\\TCPv4\\Connections Established') {
            //echo "\nChecking " . $c->CounterName . " with " . $c->CounterValue;
            $total_cons += $c->CounterValue;
            if (!isset($role_cons[$c->RoleInstance])) {
                $role_cons[$c->RoleInstance] = $c->CounterValue;
            } else {
                $role_cons[$c->RoleInstance] += $c->CounterValue;
            }
            if (!isset($rx[$c->RoleInstance])) {
                $rx[$c->RoleInstance] = 1;
            } else {
                $rx[$c->RoleInstance] += 1;
            }
            $x++;
        }
    }
    $overall_role_avg = 0;
    $rc = 0;
    $ravg = 0;
    foreach ($role_cons as $k => $v) {
        $role_cons[$k] = $v / $rx[$k];
        $ravg += $role_cons[$k];
        $rc++;
    }
    $total_cons = $ravg;
    $ravg = $ravg / $rc;
    $arr = array('cpu' => $sum / $i, 'total_connections' => $total_cons, 'avg_connections_per_role' => $ravg, 'roles' => $role_cons);
    //print_r($arr);
    return $arr;
}
/**
 * Retrieves all of the performance metric data over the $ago period
 * 
 * @param String $ago - Default: -5 minutes- Any valid Date/Time string
 * @return Object Array
 */
function get_metrics($deployment_id, $ago = "-15 minutes")
{
    global $table;
    // get DateTime.Ticks in past
    $ago = str_to_ticks($ago);
    // build query
    $filter = "DeploymentId eq '{$deployment_id}' and  Role eq 'WebRole' and PartitionKey gt '0{$ago}'";
    $filter = '';
    // run query
    $metrics = $table->retrieveEntities('WADPerformanceCountersTable', $filter);
    $arr = array();
    foreach ($metrics as $m) {
        // Global totals
        $arr['totals'][$m->countername]['count'] = !isset($arr['totals'][$m->countername]['count']) ? 1 : $arr['totals'][$m->countername]['count'] + 1;
        $arr['totals'][$m->countername]['total'] = !isset($arr['totals'][$m->countername]['total']) ? $m->countervalue : $arr['totals'][$m->countername]['total'] + $m->countervalue;
        $arr['totals'][$m->countername]['average'] = !isset($arr['totals'][$m->countername]['average']) ? $m->countervalue : $arr['totals'][$m->countername]['total'] / $arr['totals'][$m->countername]['count'];
        // Totals by instance
        $arr[$m->roleinstance][$m->countername]['count'] = !isset($arr[$m->roleinstance][$m->countername]['count']) ? 1 : $arr[$m->roleinstance][$m->countername]['count'] + 1;
        $arr[$m->roleinstance][$m->countername]['total'] = !isset($arr[$m->roleinstance][$m->countername]['total']) ? $m->countervalue : $arr[$m->roleinstance][$m->countername]['total'] + $m->countervalue;
        $arr[$m->roleinstance][$m->countername]['average'] = !isset($arr[$m->roleinstance][$m->countername]['average']) ? $m->countervalue : $arr[$m->roleinstance][$m->countername]['total'] / $arr[$m->roleinstance][$m->countername]['count'];
    }
    return $arr;
}