/**
 *  ABook Viewer for WEB
 *  Common processing for internationalization (language switching)
 *
 *  For language resource files, modify the following files according to the language you specify
 *   - ja：　lang-ja.json
 *   - ko：　lang-ko.json
 *   - en　：　lang-en.json
 *
 *  Copyright (C) Agentec Co, Ltd. All rights reserved.
 */

//Prepare objects for the global namespace
var I18N = {};

/**
 * Constant: Language file location
 */
I18N.avwsys_location = '';
I18N.avwsys_dir = '';
I18N.avwsys_storagekey = '';
I18N.avwsys_currLang = '';

/* Language initialization */
$(function () {
    I18N.initi18n();
});

/** Initialization of language resource settings */
I18N.initi18n = function () {
    I18N.avwsys_location = '/common/json/lang';
    I18N.avwsys_dir = '/abweb';
    I18N.avwsys_storagekey = 'AVWUS_Lang';
    I18N.avwsys_currLang = 'AVW_CurrLang';

    // Login screen/direct access measures
    var location = window.location.toString().toLowerCase();
    if (location.indexOf(I18N.avwsys_dir) < 0) {
        // If not under I18N.avwsys_dir directory, add I18N.avwsys_dir directory
        I18N.avwsys_location = '..' + I18N.avwsys_dir + I18N.avwsys_location;
    } else {
        // If under I18N.avwsys_dir directory, convert to relative path
        I18N.avwsys_location = '..' + I18N.avwsys_location;
    }

    var lang = 'en';
    var storage = window.localStorage;
    if (storage) {
        var lang = storage.getItem(I18N.avwsys_storagekey);
        if (!lang) {
            lang = I18N.getNavigatorLanguage();
        }
    }
    // Initialize language files
    I18N.loadLanguage(lang);
};

/* Retrieve browser language settings */
I18N.getNavigatorLanguage = function () {
    var lang = navigator.browserLanguage || navigator.language || navigator.userLanguage;
    /* Languages Supported */
    var languages = ['ja', 'ko', 'en']; // Change here if you want to add more supported languages
    if (lang.match(/ja|ko|en/g)) {
        for (var i = 0; i < languages.length; i++) {
            var index = lang.indexOf(languages[i]);
            if (index >= 0) {
                lang = lang.substring(index, 2);
                break;
            }
        }
    } else {
        lang = 'en'; // If there is no supported language, English is the default.
    }
    return lang;
};

/**
 * Language resource file loading
 * @param {*} lang
 */
I18N.loadLanguage = function (lang) {
    // Select language file from arguments
    var langfile = 'lang-' + lang + '.json';

    // Read the language file
    $.ajax({
        url: I18N.avwsys_location + '/' + langfile,
        async: false,
        dataType: 'json',
        cache: false,
        success: function (data) {
            // Rewriting the lang attribute
            document.documentElement.lang = lang;

            // Rewrite html language data
            var jsonLangData = data;
            I18N.replaceText(jsonLangData);

            // Cache language settings and language data in storage
            I18N.storeCurrentLanguage(lang, jsonLangData);
        },
        error: function (xhr, txtStatus, errorThrown) {
            var error = 'Could not load a language file ' + langfile + '. please check it.';
            error += '\n' + xhr.status + ' ' + txtStatus + ' ' + errorThrown + ' : ' + langfile;
            alert(error);
        },
    });
};

/**
 * Replace all text on the page with the language
 * @param {*} jsonLangData
 */
I18N.replaceText = function (jsonLangData) {
    var itemCount = $('.lang').length;
    if (itemCount > 0) {
        for (var i = 0; i < itemCount; i++) {
            var obj = $('.lang:eq(' + i + ')');
            var langId = obj.attr('lang');
            if (langId) {
                var langText = I18N.getLangText(jsonLangData, langId);
                var tn = obj.get()[0].localName;
                if (tn == 'input') {
                    if (obj.attr('type') == 'button' || obj.attr('type') == 'submit') {
                        obj.val(langText);
                    } else {
                        obj.text(langText);
                    }
                    const attr = obj.attr('placeholder');
                    if (typeof attr !== 'undefined' && attr !== false) {
                        obj.attr('placeholder', langText);
                    }
                } else {
                    if (obj.attr('type') == 'image') {
                        obj.attr('alt', langText);
                        obj.attr('title', langText);
                    } else {
                        obj.text(langText);
                    }
                }
            }
        }
    }
};

/* Replace HTML text with the currently set language */
I18N.i18nReplaceText = function () {
    var storage = window.sessionStorage;
    if (storage) {
        var value = storage.getItem(I18N.avwsys_storagekey);
        if (value) {
            var json = JSON.parse(value);
            I18N.replaceText(json);
        }
    }
};

/**
 * Get string from key
 * @param {*} key
 * @returns
 */
I18N.i18nText = function (key) {
    var storage = window.sessionStorage;
    if (storage) {
        var value = storage.getItem(I18N.avwsys_storagekey);
        if (value) {
            var json = JSON.parse(value);
            return I18N.getLangText(json, key);
        }
    }
    return 'undefined';
};

/**
 * Obtain strings from key values of language data
 * @param {*} jsonLangData
 * @param {*} key
 * @returns
 */
I18N.getLangText = function (jsonLangData, key) {
    if (jsonLangData) {
        var text = jsonLangData[key];
        return text;
    }
    return 'undefined.';
};

/**
 * Switching Language Data
 * @param {*} lang
 */
I18N.changeLanguage = function (lang) {
    // Store the selected language only when switching languages
    var storage = window.localStorage;
    if (storage) {
        storage.setItem(I18N.avwsys_storagekey, lang);
    }

    // Reads language files and converts text strings
    I18N.loadLanguage(lang);
};

/**
 * Save language settings
 * @param {*} lang
 * @param {*} langData
 */
I18N.storeCurrentLanguage = function (lang, langData) {
    var ss = window.sessionStorage;
    if (ss) {
        // language data
        ss.setItem(I18N.avwsys_storagekey, JSON.stringify(langData));
        // current language
        ss.setItem(I18N.avwsys_currLang, lang);
    }
};
/* Retrieving the setting language */
I18N.getCurrentLanguage = function () {
    var lang;
    var storage = window.sessionStorage;
    if (storage) {
        lang = storage.getItem(I18N.avwsys_currLang);
    }
    if (!lang) {
        lang = I18N.getNavigatorLanguage();
    }
    return lang;
};
