// ==UserScript==
// @include       http://mail.yandex.*/*
// @include       https://mail.yandex.*/*
// @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);

var idToName = {};

function checkMessagesCount() {
    var indicators = [];
    var snapshot = document.evaluate('//div[contains(@class,"b-folders__folder")]/span[@class="b-folders__folder__name"]',
                                     document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    var i;
    function make_handler(last_child) {
        return function () {
            last_child.click();
        };
    }

    for (i = 0; i < snapshot.snapshotLength; i++) {
        var node = snapshot.snapshotItem(i);

        var title = trim(node.textContent);
        if (node.parentNode.firstChild.firstChild.className === 'b-folders__counters') {
            var count = node.parentNode.firstChild.firstChild.textContent;
            if (!count.match(/^\d+/)) {
                count = '0';
            } else {
                count = count.match(/^\d+/)[0];
            }
            indicators.push({
                name: title,
                count: count,
                callback: make_handler(this.lastChild).bind(node)
            });
            idToName[node.lastChild.href.match(/#.+$/)[0]] = title;
        }
    }
    return indicators;
}

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

    reportTestState('PASS SELF TEST');
}

function messagingIndicatorSetup() {
    var indicatorsController = new Indicators(checkMessagesCount);

    window.onpopstate = function () {
        var hash = window.location.hash;
        if (idToName.hasOwnProperty(hash)) {
            indicatorsController.visited(idToName[hash]);
        }
    };

    selfTest();
}

if (document.getElementsByClassName('b-folders__counters').length) {
    Unity.init({ name: _("Yandex"),
                 domains: [['mail.yandex.com', 'http://mail.yandex.com'], ['mail.yandex.ru', 'http://mail.yandex.ru']],
                 iconUrl: "icon://unity-webapps-yandex-mail",
                 onInit: wrapCallback(messagingIndicatorSetup) });
}
