const get = require('lodash/get');

const stringSort = (k, desc) => {
    if (desc) {
        return (a, b) => {
            if (!get(a, k)) return 1;
            if (!get(b, k)) return -1;
            return get(b, k).localeCompare(get(a, k));
        };
    }
    return (a, b) => {
        if (!get(a, k)) return 1;
        if (!get(b, k)) return -1;
        return get(a, k).localeCompare(get(b, k));
    };
};

const numSort = (k, desc) => {
    if (desc) {
        return (a, b) => {
            if (!get(a, k)) return 1;
            if (!get(b, k)) return -1;
            return get(b, k) - get(a, k);
        };
    }
    return (a, b) => {
        if (!get(a, k)) return 1;
        if (!get(b, k)) return -1;
        return get(a, k) - get(b, k);
    };
};

const genAvatar = (name) => {
    let hash = 0;
    if (name.length === 0) return hash;
    // Probs don't need to hash using the whole string
    for (let i = 0; i < name.length; i += 1) {
        const chr = name.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash = hash & 10000; // We have avatars named 0-19
    }
    return `sprite${hash}`;
};

function requestAvatar(name) {
    const id = genAvatar(name);
    const req = new Request(`/assets/molecules/${id}.svg`);
    return fetch(req)
        .then(res => res.text())
        .then(svg => svg);
}

const NULL_UUID = '00000000-0000-0000-0000-000000000000';

module.exports = {
    stringSort,
    numSort,
    genAvatar,
    requestAvatar,
    NULL_UUID,
};
