class RateService {

	public Rate getLatest(String fromcur, String tocur) {
		
		LatestRate lr = latestRateRepository.findByFromcurCodeAndTocurCode(fromcur, tocur);

		if (lr != null) {
			return rateMapper.mapToRate(lr);
		}

		LatestRate lrBaseCurrency = latestRateRepository.findByFromcurCodeAndTocurCode(BASE_CURRENCY, tocur);

		LatestRate lrBaseCurrencyFromcur = latestRateRepository.findByFromcurCodeAndTocurCode(BASE_CURRENCY, fromcur);

		final BigDecimal rate;
		final SymbolEntity symbolFromcur;
		final SymbolEntity symbolTocur;

		Instant rateDate = lrBaseCurrencyFromcur.getDate();

		if (BASE_CURRENCY.equals(tocur)) {
			rate = MathUtils.invert(lrBaseCurrencyFromcur.getValue());
			symbolFromcur = lrBaseCurrencyFromcur.getTocur();
			symbolTocur = lrBaseCurrencyFromcur.getFromcur();
		} else {
			rate = MathUtils.divide(lrBaseCurrency.getValue(), lrBaseCurrencyFromcur.getValue());

			if (rateDate.isBefore(lrBaseCurrency.getDate())) {
				rateDate = lrBaseCurrency.getDate();
			}

			symbolFromcur = lrBaseCurrencyFromcur.getTocur();
			symbolTocur = lrBaseCurrency.getTocur();
		}

		return rateMapper.mapToRate(new LatestRate(symbolFromcur, symbolTocur, rate, rateDate));
	}

}