var settings = {};

function checkStatement(userNum, compType, compNum) {
    userNum = parseInt(userNum);
    compNum = parseInt(compNum);
    if (compType == 1) {
        return userNum > compNum;
    } else if (compType == 2)
        return userNum < compNum;
    else
        return userNum == compNum;
}

function updateBackgroundTwitter(names) {
    for (var name of names) {
        chrome.runtime.sendMessage({ type: "getInfo", twitterName: name }, function(response) {
            var posts = $("li [data-screen-name=" + response[3] + "]").not("[data-highlighted]");
            $.each(settings, function(i, set) {
                if (checkStatement(response[2], set.followers.type, set.followers.num) &&
                    checkStatement(response[1], set.following.type, set.following.num) &&
                    checkStatement(response[0], set.tweets.type, set.tweets.num)) {
                    $(posts).css("background", set.background);
                }
            });
            $(posts).attr("data-highlighted", "");
        });
    }
}

function updateBackgroundTweetdeck(names) {
    for (var name of names) {
        chrome.runtime.sendMessage({ type: "getInfo", twitterName: name }, function(response) {
            var posts = $("a.account-link[href='https://twitter.com/" + response[3] + "']").not("[data-highlighted]");
            $.each(settings, function(i, set) {
                if (checkStatement(response[2], set.followers.type, set.followers.num) &&
                    checkStatement(response[1], set.following.type, set.following.num) &&
                    checkStatement(response[0], set.tweets.type, set.tweets.num)) {
                    $(posts).parents("article").css("background", set.background);
                }
            });
            $(posts).attr("data-highlighted", "");
        });
    }
}

chrome.storage.local.get("highlightSettings", function(setting) {
    if (setting.highlightSettings == undefined)
        setting.highlightSettings = {};
    settings = setting.highlightSettings;
    if (window.location.hostname == 'twitter.com') {
        setInterval(function() {
            var posts = $("li [data-screen-name]").not("[data-highlighted]");
            if (!posts.length)
                return;
            var names = [];
            for (var post of posts) {
                names.push($(post).attr("data-screen-name"));
            }
            updateBackgroundTwitter($.unique(names));
        }, 1000);

    } else if (window.location.hostname == "tweetdeck.twitter.com") {
        setInterval(function() {
            var links = $("a.account-link").not("[data-highlighted]");
            if (!links.length)
                return;
            var names = [];
            for (var link of links) {
                var l = $(link).attr("href");
                names.push(l.substr(l.lastIndexOf("/") + 1));
            }
            updateBackgroundTweetdeck($.unique(names));
        }, 1000);
    }
});