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

const shapes = require('./components/shapes');

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';

const STATS = [
    { stat: 'hp', colour: 'green', svg: shapes.square },
    { stat: 'green_damage', colour: 'green', svg: shapes.diamond },
    { stat: 'red_shield', colour: 'red', svg: shapes.hexagon },
    { stat: 'red_damage', colour: 'red', svg: shapes.pentagon },
    { stat: 'blue_shield', colour: 'blue', svg: shapes.squircle },
    { stat: 'blue_damage', colour: 'blue', svg: shapes.circle },
    { stat: 'speed', colour: 'yellow', svg: shapes.triangle },
];

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