var checkable_accounts = {
    '76561198311319887': 'Weapon Crusher'
};
var ignorable_accounts = ['76561198042562877', '76561199193118161', '76561199090583973', '76561198103306049',
    '76561198093294992', '76561198109434661', '76561198080691777', '76561199209645193', '76561198176218038',
    '76561198257334931', '76561198931095630', '76561198131872819', '76561198992992515', '76561199212467171',
    '76561198077063170', '76561198425401222', '76561198894975185', '76561198838991191', '76561198340433719'];
var ignored_accounts = [];
decaled_objects = { 'Conscientious Objector': '4.00', 'Clan Pride': '2.11', 'Flair!': '4.22', 'Photo Badge': '2.44' }
backpack_page_limit = 10;

function fetchAccounts() {
    for (const [item, price] of Object.entries(decaled_objects)) {
        handleItem(item, price);
    }
}

function handleItem(item, price) {
    var stop = false;
    for (let i = 1; i <= backpack_page_limit; i++) {
        var url = 'https://backpack.tf/classifieds';
        var data = 'page=' + i + '&item=' + encodeURIComponent(item) + '&quality=6&tradable=1&craftable=1&australium=-1&killstreak_tier=0&numeric=price&comparison=lt&value=' + price + '&low=' + price;
        $.ajax({
            dataType: 'html',
            url: url,
            data: data,
            tryCount: 0,
            retryLimit: 20,
            success: function (msg) {
                if ($('.col-md-6:first .alert', msg).length > 0) {
                    stop = true;
                    return false;
                }
                $('.col-md-6:first .user-link', msg).each(function () {
                    var steam_id = $(this).attr('data-id');
                    var steam_name = $(this).attr('data-name');
                    if (ignorable_accounts.includes(steam_id)) {
                        if (!ignored_accounts.includes(steam_id)) {
                            var ignore_accounts = $('#ignored-accounts');
                            ignore_accounts.append(getHiddenAccountLink(steam_id, steam_name) + '; ');
                            ignore_accounts.fadeIn();
                            ignored_accounts.push(steam_id);
                        }

                    } else if (!(steam_id in checkable_accounts)) {
                        handleAccount(steam_id, steam_name);
                        checkable_accounts[steam_id] = steam_name;
                    }
                });
            },
            error: function (response, status, error) {
                if (response.status == 429) {
                    this.tryCount++;
                    if (this.tryCount <= this.retryLimit) {
                        setTimeout(() => {
                            $.ajax(this);
                        }, 3000 + i * 300 + this.retryCount * 70 + Math.floor(Math.random() * 1000));
                        return;
                    }
                }
            }
        });
        if (stop) {
            break;
        }
    }
}

function handleAccounts() {
    for (const [steam_id, steam_name] of Object.entries(checkable_accounts)) {
        handleAccount(steam_id, steam_name);
    }
}

function handleAccount(steam_id, steam_name) {
    var url = "https://backpack.tf/_inventory/" + steam_id;
    $.ajax({
        dataType: 'json',
        url: url,
        tryCount: 0,
        retryLimit: 30,
        success: function (msg) { handleHTML(steam_id, steam_name, msg['html']); },
        error: function (response, status, error) {
            this.tryCount++;
            if (this.tryCount <= this.retryLimit) {
                setTimeout(() => {
                    $.ajax(this);
                }, 3000 + this.tryCount * 40 + Math.floor(Math.random() * 1000));
                return;
            }
        }
    });
}

function getHiddenAccountLink(steam_id, steam_name) {
    return '<a href="https://next.backpack.tf/profiles/' + steam_id + '">' + steam_name + '</a>';
}

function previewFilteredItem() {
    $('li', $(this)).fadeIn(100)
}

function hideFilteredItem() {
    $('li', $(this)).fadeOut(100)
}

function handleHTML(steam_id, steam_name, html_string) {
    var html = $.parseHTML(html_string);
    var filtered_item_count = 0;
    var filtered_item_previews = [];
    var decaled_items = $('div.decal', html);
    if (decaled_items.length == 0) {
        var empty_accounts = $('#empty-accounts');
        empty_accounts.append(getHiddenAccountLink(steam_id, steam_name) + '; ');
        empty_accounts.fadeIn();
        return false;
    }
    var inventory = $('<div class="inventory"></div>');
    inventory.append('<a href="https://next.backpack.tf/profiles/' + steam_id + '"><h3>' + steam_name + '</h3></a>');
    decaled_items.each(function () {
        var parent = $(this).parent();
        var is_strange = parent.hasClass('q-440-11');
        var is_uncraftable = parent.hasClass('nocraft');
        var is_untradable = parent.hasClass('notrade');
        var is_price_in_keys = $('.bottom-right span', parent).text().includes('key');
        var url = "https://next.backpack.tf/item/" + parent.attr('data-id');
        var a = $('<a href="' + url + '"></a>');
        a.append(parent);
        if (is_strange || is_uncraftable  || is_untradable || is_price_in_keys) {
            filtered_item_count++;
            parent.addClass('filtered-item');
            a.on("mouseenter", previewFilteredItem).on("mouseleave", hideFilteredItem)
            a.append(filtered_item_count);
            var separator = '';
            if (filtered_item_previews.length) {
                separator = ', ';
            }
            filtered_item_previews.push(separator, a)
            return;
        }
        inventory.append(a);
    });
    if (filtered_item_count) {
        var link = getHiddenAccountLink(steam_id, steam_name);
        $('#filtered-accounts').append(link, ' (', filtered_item_previews, '); ');
        $('#filtered-accounts').fadeIn();
    }
    var item_count = inventory.children().length - 1;
    if (item_count <= 0) {
        return false;
    }
    var inventories = $('.inventory');
    if (inventories.length > 0) {
        inventory.attr('data-items', item_count);
        var last_div = null;
        inventories.each(function () {
            if (item_count > $(this).children().length) {
                return false;
            }
            last_div = $(this);
        });
        if (last_div) {
            last_div.after(inventory);
        } else {
            $('body').prepend(inventory);
        }
    } else {
        $('#filtered-accounts').before(inventory);
    }
}

$(document).ready(function () {
    handleAccounts();
    fetchAccounts();
});