// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
// ==UserScript==
// @include       http://*.facebook.com/*
// @include       https://*.facebook.com/*
// @include       https://*.facebook.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 isCorrectPage() {
    var i, ids = ['mercurymessagesCountValue'];

    for (i = 0; i < ids.length; i++) {
        if (!document.getElementById(ids[i])) {
            return false;
        }
    }

    return true;
}

function getMessageCountElement() {
    return document.getElementById('mercurymessagesCountValue');
}

function getNotificationCountElement() {
    return document.getElementById('notificationsCountValue');
}

function selfTest() {
    if (!getMessageCountElement()) {
        reportTestState('FAILED: getMessageCountElement is null');
        return;
    }

    if (!getNotificationCountElement()) {
        reportTestState('FAILED: getNotificationCountElement is null');
        return;
    }

    reportTestState('PASS SELF TEST');
}

function messagingIndicatorSetup() {
    if (!isCorrectPage()) {
        return;
    }
    var countElement = getMessageCountElement();
    var notificationElement = getNotificationCountElement();

    function checkMessagesCount() {
        var indicators = [];
        function makeCallback(node) {
            return function () { launchClickEvent(node.parentNode); };
        }
        indicators.push({ name: _("Messages"),
                          count: countElement.textContent,
                          callback: makeCallback(countElement) });
        indicators.push({ name: _("Notifications"),
                          count: notificationElement.textContent,
                          callback: makeCallback(notificationElement) });
        return indicators;
    }
    var indicatorsController = new Indicators(checkMessagesCount);

    if (document.location.hostname === 'apps.facebook.com') {
        var name = document.evaluate('//div[@role="contentinfo"]/div/span', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.textContent;
        linkVisited(document.location.toString(), name);
    }

    selfTest();
}

if (document.getElementById('email')) {
    var email = document.getElementById('email');

    window.onunload = function () {
        localStorage.setItem('login', email.value);
    };
}

var login = localStorage.getItem('login');
if (!login) {
    login = null;
}

Unity.init({ name: "FacebookMessenger",
             iconUrl: "icon://unity-webapps-facebook",
             login: login,
             domain: 'facebook.com',
             homepage: 'https://www.facebook.com/',
             onInit: wrapCallback(messagingIndicatorSetup) });
