<?php

function formatPrice($amount, $currencyId) {
	$formatter = new NumberFormatter(sfContext::getInstance()->getUser()->getCulture(), NumberFormatter::CURRENCY);
	return $formatter->formatCurrency($amount, $currencyId);
}

function formatRate($rate) {
	$formatter = new NumberFormatter(sfContext::getInstance()->getUser()->getCulture(), NumberFormatter::PERCENT);
	$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
	return $formatter->format($rate, NumberFormatter::TYPE_DOUBLE);
}

function formatTax(BillingTaxZone $taxZone, $currencyId = false) {
	if (!(int)$taxZone->taxZoneAmountType) {
		$formatter = new NumberFormatter(sfContext::getInstance()->getUser()->getCulture(), NumberFormatter::PERCENT);
		$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
		return $formatter->format((float)$taxZone->taxZoneAmount / 100, NumberFormatter::TYPE_DOUBLE);
	} else {
		$formatter = new NumberFormatter(sfContext::getInstance()->getUser()->getCulture(), NumberFormatter::CURRENCY);
		$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
		return $formatter->formatCurrency((float)$taxZone->taxZoneAmount, $currencyId);
	}
}

function formatProductName($productName) {
	$words = explode(' ', $productName);
	$resultWords = array();
	foreach ($words as $word) {
		$resultWords[] = (
			mb_strlen($word, "UTF-8") > 20 ?
			mb_substr($word, 0, 10, "UTF-8") . "..." . mb_substr($word, mb_strlen($word, "UTF-8") - 10, mb_strlen($word, "UTF-8"), "UTF-8") :
			$word
		);
	}
	return implode(' ', $resultWords);
}

function formatContinueShoppingUrl($container) {
	if ($widget = ResourceLocator::getInstance()->billingWidgetService->getByCode($container)) {
		return $widget->continueShoppingUrl;
	}

	if ($store = ResourceLocator::getInstance()->billingStoreService->getByCode($container)) {
		return $store->continueShoppingUrl;
	}

	return url_for('@catalog?container='.$container);
}