/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var avatar_cache = [];


/**
 * Get svg for a player's avatar
 * Caches generated icons to eliminate performance penalty for repeated calls
 * @param {int} playerid
 * @param {int} teamid
 * @param {boolean} asdata true to return base64 data URI, false to return svg
 * markup
 * @returns {string}
 */
function getAvatarIcon(playerid, teamid, asdata) {
    if (avatar_cache[playerid] == null) {
        console.log("Generating avatar icon for account id", playerid);
        var svg = renderSvgIcon(playerid, SETTINGS["teams"][teamid]["hue"]);
        var data = svgToData(svg);
        avatar_cache[playerid] = {"svg": svg, "data": data};
    }
    if ((typeof asdata == "boolean") && (asdata == true)) {
        return avatar_cache[playerid].data;
    }
    return avatar_cache[playerid].svg;
}

/**
 * Generate an abstract icon and return SVG code for it
 * @param {String} data Different data, different icon
 * @param {int} hue (optional) the icon hue
 * @returns {String}
 */
function renderSvgIcon(data, hue) {
    var hues = [];
    if (typeof hue != "undefined") {
        hues = [hue];
    }
    // Custom identicon style
    // https://jdenticon.com/icon-designer.html?config=214726c41105452e42552f41
    window.jdenticon_config = {
        hues: hues,
        lightness: {
            color: [0.67, 0.86],
            grayscale: [0.48, 0.65]
        },
        saturation: {
            color: 0.69,
            grayscale: 0.47
        },
        backColor: "#00000000"
    };

    return jdenticon.toSvg(data, 100);
}

/**
 * Convert a SVG string to a data URL
 * @param {String} svg
 * @returns {String}
 */
function svgToData(svg) {
    return "data:image/svg+xml;base64," + window.btoa(svg);
}