// ==UserScript==
// @include       https://twitter.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 getProfileLinkNode() {
    return document.evaluate('//a[@data-nav="profile"]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}

function isCorrectPage() {
    var i, ids = ['doc', 'banners', 'page-outer', 'global-nav-home', 'global-new-tweet-button'];

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

    return true;
}

var currentIndicator = '';

function checkMessagesCount() {
    var indicators = [];
    var title;
    var search = document.getElementsByClassName('search-query')[0];
    if (search) { // stream for #tag
        title = search.textContent;
    }
    if (document.getElementsByClassName('module mini-profile')[0]) { // home screen
        title = _("Tweets");
    }

    if (title) {
        var count = '0';
        var countElement = document.getElementsByClassName('new-tweets-bar js-new-tweets-bar')[0];
        if (countElement) {
            count = countElement.textContent.match(/\d+/)[0];
        }
        reportTestState(title + count);
        // empty callback raise current tab
        indicators.push({ name: title, count: count, callback: function () {} });
        currentIndicator = title;
    }
    return indicators;
}

/**
 * Validates the page for functional tests.
 *
 */
function selfTest() {
    if (!getProfileLinkNode() || !getProfileLinkNode().href) {
        return;
    }
    if (!checkMessagesCount().length) {
        return;
    }

    reportTestState('PASS SELF TEST');
}

function messagingIndicatorSetup() {
    var indicatorsController = new Indicators(checkMessagesCount);
    indicatorsController.visited(currentIndicator);
}

var login;
var callback;
if (isCorrectPage()) {
    var prefix = 'https://twitter.com/';

    var profileLink = getProfileLinkNode();
    if (profileLink && profileLink.href) {
        login = profileLink.href;

        if (login.substr(0, prefix.length) === prefix) {
            login = login.substr(prefix.length);
        } else {
            login = null;
        }
    }

    callback = wrapCallback(messagingIndicatorSetup);

    selfTest();
}
Unity.init({ name: "Twitter",
             login: login,
             domain: 'twitter.com',
             homepage: 'https://twitter.com/',
             iconUrl: "icon://unity-webapps-twitter",
             onInit: callback });
