<?php

namespace Fifa\ConnectId\Sdk\Registration;

use Fifa\ConnectId\Sdk\ApiClient\Async\WaitTimeStrategyInterface;

class CachePollingResponseAwaiter implements ResponseAwaiterInterface
{
    /**
     * @var CorrelationIdBasedItemProviderInterface
     */
    private $cacheStorage;

    /**
     * @var WaitTimeStrategyInterface
     */
    private $waitTimeStrategy;

    public function __construct(CorrelationIdBasedItemProviderInterface $responsesCache, WaitTimeStrategyInterface $waitTimeStrategy)
    {
        $this->cacheStorage = $responsesCache;
        $this->waitTimeStrategy = $waitTimeStrategy;
    }

    /**
     * @inheritDoc
     */
    public function waitForResponse(string $correlationId, int $timeoutSeconds)
    {
        $attempt = 0;
        $startTime = time();

        while (time() < $startTime + $timeoutSeconds) {
            $response = $this->cacheStorage->getByCorrelationId($correlationId);
            if ($response != null) {
                return $response;
            }

            usleep($this->waitTimeStrategy->next(++$attempt));

            $elapsed = time() - $startTime;
            $this->waitTimeStrategy->feedback($elapsed);
        }

        return null;
    }
}