<?php

namespace KupShop\I18nBundle\Util;

use KupShop\I18nBundle\Entity\Currency;
use KupShop\KupShopBundle\Context\CurrencyContext;
use KupShop\KupShopBundle\Util\Contexts;

class PriceConverter
{
    protected $currencies = [];

    public function convert($fromCurrency, $toCurrency, $price): \Decimal
    {
        return $this->convertPrice(
            $this->getCurrency($fromCurrency),
            $this->getCurrency($toCurrency),
            \Decimal::create($price)
        );
    }

    public function convertPrice(Currency $fromCurrency, Currency $toCurrency, \Decimal $price): \Decimal
    {
        if ($fromCurrency->getId() == $toCurrency->getId()) {
            return $price;
        }

        $price = $price->mul($fromCurrency->getRate());
        $price = $price->div($toCurrency->getRate());

        return $price;
    }

    public function getCurrency($currency): ?Currency
    {
        if ($currency instanceof Currency) {
            return $currency;
        }

        return $this->getCurrencies()[$currency] ?? null;
    }

    private function getCurrencies(): array
    {
        if (empty($this->currencies)) {
            $this->currencies = Contexts::get(CurrencyContext::class)->getAll();
        }

        return $this->currencies;
    }
}
