<?php
namespace Incoviba\Service;

use DateTimeInterface;
use DateTimeImmutable;
use Incoviba\Common\Implement\Exception\EmptyRedis;

class USD
{
    protected string $redisKey = 'usd';

    public function __construct(protected Redis $redisService, protected Money $moneyService) {}

    public function get(?DateTimeInterface $date = null): float
    {
        if ($date === null) {
            $date = new DateTimeImmutable();
        }
        $usds = [];
        try {
            $usds = json_decode($this->redisService->get($this->redisKey), JSON_OBJECT_AS_ARRAY);
            if (!isset($usds[$date->format('Y-m-d')])) {
                throw new EmptyRedis($this->redisKey);
            }
            $usd = $usds[$date->format('Y-m-d')];
        } catch (EmptyRedis) {
            $usd = $this->moneyService->getUSD($date);
            $usds[$date->format('Y-m-d')] = $usd;
            ksort($usds);
            $this->redisService->set($this->redisKey, json_encode($usds), 60 * 60 * 24 * 30);
        }
        return $usd;
    }
}
