// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {Localizer}
 */
define(['hp/core/Language', 'hp/services/Log', 'hp/model/DevelopmentSettings', 'lang/en', 'jquery', 'lib/jquery.timeago'],

function(LANG, log, settings, englishData) {"use strict";

    var Localizer = ( function() {
        /**
         * @constructor
         * @type {Localizer}
         */
        function Localizer() {
            var factor = settings.getLabelLengthFactor();

            function valueForKey(key, data) {
                var keys, value, _i, _len;
                keys = key.split(/\./);
                value = data;
                for( _i = 0, _len = keys.length; _i < _len; _i++) {
                    key = keys[_i];
                    value = value ? value[key] : null;
                }
                return value;
            }

            /**
             * Test if a particular localization key exists and has a non-null value.
             * @return true if the key exists and has a non-null value. False otherwise.
             */
            this.hasValueForKey = function(key) {
                return valueForKey(key, LANG.getBundle()) ? true : false;
            };

            /**
             * Get the string resource associated with the specified key.
             * @param key The hiearchical resource key. For example "core.common.yes"
             * @param args An array of values to substitute for any {<number>} tokens in the string.
             *     {0} is replaced with args[0], etc.
             */
            this.getString = function(key, args) {
                var data, str, i, regexp;
                data = LANG.getBundle();
                str = valueForKey(key, data);



                // Fallback to english if needed
                if(!str && (hp.getLang() != 'en')) {
                    str = valueForKey(key, englishData);
                    if (str) {
                        log.warn("Localized message for key '" + key + "' does not exist for " +
                                hp.getLang() + ".");
                    }
                }

                //ERROR for bad lookup!
                if(!str) {
                    log.error("Localized message for key '" + key + "' does not exist.");
                } else if(args) {
                    for( i = 0; i < args.length; i++) {
                        regexp = new RegExp('\\{' + i + '\\}', "g");
                        str = str.replace(regexp, args[i]);
                    }
                }

                if (str) {
                    //an English term might get very long in other languages.
                    //To test localization, make the string longer based on the factor, default to 0
                    for (i = 0; i < factor; i++)
                    	str  += str;
                }

                return str ? str : "";
            };

            //TODO clean up a little bit.
            //Pulled with minor modification from jquery.localize MIT license (https://github.com/coderifous/jquery-localize)
            function localize(elems) {
                var data = LANG.getBundle();
                return elems.each(function() {
                    var elem, key, value;
                    elem = $(this);
                    key = elem.data('localize');
                    if (!key) {
                        key = elem.attr("rel").match(/localize\[(.*?)\]/)[1];
                    }
                    value = valueForKey(key, data);

                    // Fallback to english if needed
                    if(!value && (hp.getLang() != 'en')) {
                        value = valueForKey(key, englishData);
                        if (value) {
                            log.warn("Localized message for dom key '" + key + "' does not exist for " +
                                    hp.getLang() + ".");
                        }
                    }

                    if(value) {
                        //an English term might get very long in other languages.
                        //To test localization, make the string longer based on the labelLengthFactor, default to 0
                        for (var i = 0; i < factor; i++) {
                        	value  += value;
                        }

                        if(elem.is('input')) {
                            if(elem.is("[placeholder]")) {
                                return elem.attr("placeholder", value);
                            } else {
                                return elem.val(value);
                            }
                        } else if(elem.is('optgroup')) {
                            return elem.attr("label", value);
                        } else if(elem.is('img')) {
                            value = valueForKey("" + key + ".alt", data);
                            if(value != null) {
                                elem.attr("alt", value);
                            }
                            value = valueForKey("" + key + ".src", data);
                            if(value != null) {
                                return elem.attr("src", value);
                            }
                        } else {
                            return elem.html(value);
                        }
                    } else {
                        log.error("Localized message for dom key '" + key + "' does not exist.");
                    }
                    return elem;
                });
            }


            this.localizeDom = function(startElement) {
                localize($('[data-localize],[rel*="localize"]', ( startElement ? startElement : window.document)));
            };

            this.formatRestError = function(msg, error) {
                var restMsg = this.getString('core.rest_error_fmt',
                        [msg, error.errorMessage, error.resolution]);
                return restMsg;
            };

            this.init = function() {
                // setup strings used by timeago plugin
                $.timeago.settings.strings = this.getString('core.timeago');
                // localize what's currently on the page.
                this.localizeDom();
            };
        }

        return new Localizer();
    }());

    return Localizer;
});
