<?php
namespace Incoviba\Service;

use DateTimeInterface;
use Psr\Log\LoggerInterface;
use Incoviba\Common\Define\Money\Provider;
use Incoviba\Common\Implement\Exception\EmptyResponse;
use Incoviba\Service\Money\MiIndicador;

class Money
{
    public function __construct(protected LoggerInterface $logger) {}

    protected array $providers;
    public function register(string $name, Provider $provider): Money
    {
        if (isset($this->providers) and isset($this->providers[$name]) and $this->providers[$name] === $provider) {
            return $this;
        }
        $this->providers[$name] = $provider;
        return $this;
    }
    public function getProvider(string $name): Provider
    {
        return $this->providers[$name];
    }

    public function get(string $provider, DateTimeInterface $dateTime): float
    {
        try {
            return $this->getProvider($provider)->get(MiIndicador::getSymbol($provider), $dateTime);
        } catch (EmptyResponse) {
            return 0;
        }
    }
    public function getUF(DateTimeInterface $dateTime): float
    {
        try {
            return $this->getProvider('uf')->get(MiIndicador::UF, $dateTime);
        } catch (EmptyResponse) {
            return 0;
        }
    }
    public function getIPC(DateTimeInterface $start, DateTimeInterface $end): float
    {
        if ($start >= $end) {
            return 0;
        }
        try {
            return $this->getProvider('ipc')->getVar($start, $end);
        } catch (EmptyResponse) {
            return 0;
        }
    }
    public function getUSD(DateTimeInterface $dateTime): float
    {
        try {
            return $this->getProvider('usd')->get(MiIndicador::USD, $dateTime);
        } catch (EmptyResponse $exception) {
            $this->logger->critical($exception);
            return 0;
        }
    }
}
