DeKleineKobini / TORN: Museum Market

// ==UserScript==
// @name         TORN: Museum Market
// @description  Show inventory amount, meant for museum items.
// @version      1.1.1
// @author       DeKleineKobini
// @updateURL    https://openuserjs.org/meta/DeKleineKobini/TORN_Museum_Market.meta.js
// @downloadURL  https://openuserjs.org/install/DeKleineKobini/TORN_Museum_Market.user.js
// @match        https://www.torn.com/imarket.php*
// @license      MIT
// @require      https://openuserjs.org/src/libs/DeKleineKobini/DKK_Torn_Utilities.js
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

var settings = {
    types: ["flowers", "plushies"],
    cache: 15 * 60 * 1000 // default: 15 minutes
}

setDebug(false);

/* --------------------
CODE - EDIT ON OWN RISK
-------------------- */
setPrefixEasy("MM");
requireAPI();

var inventory = [];
var jsonLast;

getCache("museummarket-inventory").then(result => {
    if (result) inventory = result;
    else refreshInventory();
});

refreshInventory();

observeMutations(document, ".content-title-links", true, (mut, obs) => {
    $(".content-title-links").append("<a role='button' id='refreshInventory' class='dd-important t-clear h c-pointer m-icon line-h24 right'><span>Refresh Inventory</span></a>")

    $("#refreshInventory").click(() => refreshInventory());
}, {
    childList: true,
    subtree: true
});

xhrIntercept((page, json, uri) => {
    if (page != "imarket" || !json) return;

    jsonLast = json;

    showAmounts();
});

function refreshInventory(onFinish) {
    log("Refresh the inventory.");
    sendAPIRequest("user", null, "inventory").then(resultApi => {
        if (resultApi.inventory) {
            inventory = resultApi.inventory;
            setCache("museummarket-inventory", resultApi.inventory, settings.cache);
            if (onFinish) onFinish();
        }
    });
}

function showAmounts() {
    if (!jsonLast) return

    let category = $(".market-tabs li[aria-selected='true']").attr("data-cat");
    if (!settings.types.includes(category)) return;

    debug("json", jsonLast)

    let items = {};
    jsonLast.forEach(item => {
        let apiItems = inventory.filter(it => {
            return it.ID == item.itemID
        });

        let id = item.itemID;
        let amount = apiItems.length ? apiItems[0].quantity : 0;

        items[id] = amount;
    });

    observeMutations($("#" + category + " .m-items-list")[0],
                     ".m-item-wrap", true,
                     (mut, obs) => Object.keys(items).forEach(i => $(".m-item-wrap:has(div[itemid=" + i + "]) .qty").html(items[i])), {
        attributes: true,
        childList: true
    });

}