// ==UserScript==
// @include        http://*.reddit.com/
// @include        http://reddit.com/*
// @include        http://*.reddit.com/*
// @require        utils.js
// ==/UserScript==

// This placeholder gets munged with real data at build time.
var WebappsGettextDict = JSON.parse(unescape(
    "%7B%22GETTEXT%22%3A%22PLACEHOLDER%22%7D"
));

window.Unity = external.getUnityObject(1);

function setupIndicators() {
    Unity.MessagingIndicator.showIndicator(_("Inbox"), {
        count: document.getElementsByClassName("havemail")[0] !== undefined
    });

    Unity.MessagingIndicator.addAction(_("Compose New Message"),
                                       makeRedirector("http://www.reddit.com/message/compose/"));
}

function setKarmaCount() {
    var userkarma = document.getElementsByClassName("userkarma")[0];
    if (userkarma === null) {
        return;
    }
    Unity.Launcher.setCount(Number(userkarma.textContent));
}

function getSubredditList() {
    var subredditBar = document.getElementById("sr-bar");
    var links = subredditBar.getElementsByTagName("a"), i, link;
    var subreddits = [];
    for (i = 0; i < links.length; i++) {
        link = links[i];
        subreddits.push(link.textContent);
    }

    return subreddits;
}

function getSubredditRedirector(subredditName) {
    return makeRedirector("http://www.reddit.com/r/" + subredditName);
}

function addSubredditAction(subredditName) {
    Unity.addAction("/" + subredditName, getSubredditRedirector(subredditName));
}

function addSubredditActions() {
    var subreddits = getSubredditList(), i;
    for (i = 0; i < subreddits.length; i++) {
        var subreddit = subreddits[i];
        addSubredditAction(subreddit);
    }
}

function onInit() {
    try {
        setupIndicators();
    } catch (x) {
        console.log("Exception setting up reddit indicators: " + x.toString());
    }
    try {
        addSubredditActions();
    } catch (y) {
        console.log("Exception setting up reddit actions: " + y.toString());
    }
    try {
        setKarmaCount();
    } catch (z) {
        console.log("Exception fetching reddit karma: " + z.toString());
    }
}

Unity.init({ name: "Reddit",
             domain: 'reddit.com',
             homepage: 'http://www.reddit.com',
             iconUrl: "icon://unity-webapps-reddit",
             onInit: wrapCallback(onInit) });
