#!/usr/bin/env php
<?php
use Ackintosh\Ganesha\Storage\Adapter\TumblingTimeWindowInterface;

require_once dirname(__DIR__) . '/common.php';
echo "[ settings ]\n";
echo "time window : " . TIME_WINDOW . "s\n";
echo "failure rate : " . FAILURE_RATE . "%\n";
echo "minumum requests : " . MINIMUM_REQUESTS . "\n";
echo "interval to half open : " . INTERVAL_TO_HALF_OPEN . "s\n";
echo "\n";

echo "[ failure rate ]\n";

$storage = $argv[1] ?: 'redis';

$ganesha = buildGanesha($storage);
$prop = new \ReflectionProperty($ganesha, 'strategy');
$prop->setAccessible(true);
$strategy = $prop->getValue($ganesha);

// current
$prop = new \ReflectionProperty($strategy, 'storage');
$prop->setAccessible(true);
$storage = $prop->getValue($strategy);

$failure = $storage->getFailureCount(SERVICE);
$success = $storage->getSuccessCount(SERVICE);
$rejection = $storage->getRejectionCount(SERVICE);

$total = $failure + $success + $rejection;
$rate = $total ? ($failure / ($failure + $success)) * 100 : 0;
echo sprintf("current : %.2F %%\n", $rate);

if ($storage instanceof TumblingTimeWindowInterface) {
    // previous
    $method = new \ReflectionMethod($strategy, 'keyForPreviousTimeWindow');
    $method->setAccessible(true);
    $key = $method->invokeArgs($strategy, [SERVICE, TIME_WINDOW]);

    $failure = $storage->getFailureCountByCustomKey($key);
    $success = $storage->getSuccessCountByCustomKey($key);
    $rejection = $storage->getRejectionCountByCustomKey($key);

    $total = $failure + $success + $rejection;
    $rate = $total ? ($failure / ($failure + $success)) * 100 : 0;
    echo sprintf("previous : %.2F %%\n", $rate);
}

