/* global Intl */

/**
 *
 * @constructor
 */
function Currency (code, symbol, fractionDigit, symbolBefore, formatFunction) {
    this.code = code;
    this.symbol = symbol;
    this.fractionDigit = fractionDigit;
    this.symbolBefore = symbolBefore;
    var multiplicator = 1;
    for(var i = 0; i < fractionDigit; i++) {
        multiplicator = multiplicator * 10;
    }
    this.subunitMultiplicator = multiplicator;
    if (formatFunction) {
        this.formatFunction = formatFunction;
    }
};

Currency.prototype.formatAmount = function (moneyLong, locale) {
    var decimalValue = moneyLong / (this.subunitMultiplicator);
    if (this.formatFunction) {
        return this.formatFunction(decimalValue, locale);
    } else {
        return decimalValue.toLocaleString(locale, {
            style: "currency",
            currency: this.code
        });
    }
};

Currency.prototype.toDecimalValue = function (moneyLong) {
    return moneyLong / (this.subunitMultiplicator);
};

Currency.MAP = {};

Currency.formatAmount = function (moneyLong, currencyCode, locale) {
    var currency = Currency.get(currencyCode);
    return currency.formatAmount(moneyLong, locale);
};

Currency.toDecimalValue = function (moneyLong, currencyCode) {
    var currency = Currency.get(currencyCode);
    return currency.toDecimalValue(moneyLong);
};

/**
 * 
 * @param {String} code
 * @returns {Currency}
 */
Currency.get = function (code) {
    if (Currency.MAP.hasOwnProperty(code)) {
        return Currency.MAP[code];
    }
    var currency;
    var symbolBefore = _isSymbolBefore(code);
    if (code === 'CFA') {
        currency = new Currency("CFA", "CFA", 0, symbolBefore, function(decimalValue, locale) {
            return decimalValue.toLocaleString(locale, {
                style: "decimal",
                maximumFractionDigits: 0
            }) + " CFA";
        });
    } else {
        var numberFormat = new Intl.NumberFormat('en', { style: 'currency', currency: code });
        var options = numberFormat.resolvedOptions();
        var fractionDigit = options.maximumFractionDigits;
        var format = numberFormat.format(987);
        var idx = format.indexOf(9);
        var symbol = format.substring(0, idx);
        currency = new Currency(code, symbol, fractionDigit, symbolBefore);
    }
    Currency.MAP[code] = currency;
    return currency;
    
    function _isSymbolBefore (code) {
        switch(code) {
            case "USD":
            case "GBP":
                return true;
            default:
                return false;
        }
    }
};

