/**
 * Created by aheadware
 */

"use strict";

var app = app || {};
app.util = app.util || {};

/**
 *
 * @type {{expose, format, init, setLang}}
 */
app.util.Locale = (function(){

    var dictionary,
        language,
        defaultLanguage;

    return {

        expose : function( fnName )
        {
            if ( window )
            {
                window[ fnName ] = this.format.bind(this);
            }
        }
        ,

        /**
         *
         * @param key
         * @param params
         * @returns {*}
         */
        format : function( key, params )
        {
            if ( dictionary[ language ].hasOwnProperty( key ) )
            {
                return dictionary[ language][ key ].replace(/{(\d+)}/g, function(match, number)
                {
                    return typeof params[number] != 'undefined'
                        ? params[number]
                        : match
                        ;
                });
            }
            else if ( defaultLanguage && dictionary[ defaultLanguage ].hasOwnProperty( key ) )
            {
                return dictionary[ defaultLanguage ][ key ].replace(/{(\d+)}/g, function(match, number)
                {
                    return typeof params[number] != 'undefined'
                        ? params[number]
                        : match
                        ;
                });
            }
            else
            {
                return '###' + key + '###';
            }
        }
        ,
        /**
         *
         * @param dict
         */
        init : function( dict, defLang )
        {
            dictionary = dict || {};

            if ( !defLang && Object.keys( dictionary ).length > 0 )
            {
                // If no default language is specified, we use the first translation of the current dictionary
                defaultLanguage = Object.keys( dictionary )[ 0 ];
                language = defaultLanguage;
            }
            else
            {
                language = defaultLanguage;
            }
        }
        ,
        /**
         *
         * @param l Language key
         * @param dl Default language key
         * @returns {boolean}
         */
        setLang : function( lang, defaultLang )
        {
            if ( !dictionary || !dictionary.hasOwnProperty( lang ) )
            {
                throw new Error( 'Invalid dictionary' );
            }

            language = lang;

            if ( defaultLang && dictionary.hasOwnProperty( defaultLang ) )
            {
                defaultLanguage = defaultLang;
            }
        },
    };

})();