// This module keeps track of achievements that are displayed
// to the user as badges or trophies, usually on the menu page
// Right now this information is kept in localstorage. This
// is for test purposes, eventually it will be kept as part of the
// game state in a database.

// badgeState has the following format
//
// badgeState = {
//                 activity1: {
//                               count: n, // number of times activity was completed (may be zero)
//                               badge: "badge type", // string indicating the badge to be displayed (medal, trophy, etc.)
//                  },
//                 activity2: {
//                               count: n, // number of times activity was completed (may be zero)
//                               badge: "badge type", // string indicating the badge to be displayed (medal, trophy, etc.)
//                  },
//                  etc...
//               };

const badgeKey = "badge-state-7gen";

function addBadge({activity, badge}) {
    let badgeState = getBadgeState();
    if (activity in badgeState) {
        badgeState[activity].count += 1;
        if (badge) {
            badgeState[activity].badge = badge;
        }
    }
    else {
        badgeState[activity] = {
            count: 1,
            badge
        }
    }
    localStorage.setItem(badgeKey, JSON.stringify(badgeState));
}

function setBadge({activity, badge, count}) {
    let badgeState = getBadgeState();
    badgeState[activity] = {
        count,
        badge
    };
    localStorage.setItem(badgeKey, JSON.stringify(badgeState));
}

function getBadgeState() {
    const badgeStateJSON = localStorage.getItem(badgeKey);
    let badgeState;
    if (badgeStateJSON === null) {
        badgeState = {};
        localStorage.setItem(badgeKey, JSON.stringify(badgeState));
    }
    else {
        try {
            badgeState = JSON.parse(badgeStateJSON);
        }
        catch (err) {
            console.log(err);
            badgeState = {};
        }
    }
    return badgeState;
}

function clearAllBadges() {
    let badgeState = {};
    localStorage.setItem(badgeKey, JSON.stringify(badgeState));
}

export {getBadgeState, addBadge, setBadge, clearAllBadges};