const identifierLocalStorageKey = 'reactoo-id';

const getFingerPrint = function (instanceType = '', salt = '') {
    return Promise.resolve(generateFingerprint(getRandomNumberGenerator(getId() + instanceType + salt)));
}

const generateFingerprint = function (randomNumberGenerator) {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (randomNumberGenerator()*16)%16 | 0;
        return (c==='x' ? r : (r&0x3|0x8)).toString(16);
    });
};

const getId = function () {
    let id = localStorage.getItem(identifierLocalStorageKey);
    if (!id) {
        id = Math.round(Math.random() * Math.pow(10, 16)) + '';
        localStorage.setItem(identifierLocalStorageKey, id);
    }
    return id;
}

const getRandomNumberGenerator = function (seed) {
    seed = (seed || Math.floor(Math.random() * 10000000000000000)) + '';

    // https://stackoverflow.com/a/47593316/3162532 - xmur3
    let i, h;
    for (i = 0, h = 1779033703 ^ seed.length; i < seed.length; i++) {
        h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
        h = h << 13 | h >>> 19;
    }

    h = Math.imul(h ^ h >>> 16, 2246822507);
    h = Math.imul(h ^ h >>> 13, 3266489909);
    seed = (h ^ h >>> 16) >>> 0;

    // https://stackoverflow.com/a/47593316/3162532 - Mulberry32
    return function () {
        let t = seed += 0x6D2B79F5;
        t = Math.imul(t ^ t >>> 15, t | 1);
        t ^= t + Math.imul(t ^ t >>> 7, t | 61);
        return ((t ^ t >>> 14) >>> 0) / 4294967296;
    };
}

export {getFingerPrint};
