// ==UserScript==
// @include        https://mail.google.com/*
// @require        utils.js
// @require        validate.js
// @require        google-common.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 getNumber(str) {
    try {
        var onlyNumber = str.match(/\(([0-9]|,|\s)+\)/)[0].match(/([0-9]|,|\s)+/)[0];

        return onlyNumber.replace(/(,|\s)/g, "");
    } catch (x) {
        return '0';
    }
}


var interestNodes = {
    login: {
        name: 'login',
        query: '//div[@role="navigation"]//*[contains(text(), "@")]',
        validator: function (node) {
            return node.textContent.match(/^.*@.*\.{1}.*$/) !== null;
        },
        fragment: '<div role="navigation"><span>example@example.com</span></div>'
    },
    compose: {
        name: "compose button",
        query: '//div[@role="navigation"]/div[1]/div[1]/div[1][@role="button"]',
        fragment: ''
    },
    labels: {
        name: 'Labels',
        query: '//div[@role="navigation"]/div[2]//a[contains(@href, "#label")]',
        fragment: '',
        value: function (node) {
            return getNumber(node.textContent);
        }
    },
    inbox: {
        name: "Inbox",
        query: '//div[@role="navigation"]/div[2]//a[contains(@href, "#inbox")]',
        fragment: '',
        value: function (node) {
            return getNumber(node.text);
        }
    },
    pane: {
        name: 'pane',
        query: '//div[@role="navigation"]'
    }
};

function getComposeMessageNode() {
    return validatedNode(interestNodes.compose);
}


function getLabels() {
    var i, res = [];

    var labelNodes = validatedNodes(interestNodes.labels);

    for (i = 0; i < labelNodes.length; i++) {
        var node = labelNodes[i];

        try {
            res.push({ name: unescape(node.href.match(/#label\/(.+)$/)[1]),
                       count: validatedNodeValue(interestNodes.labels, node),
                       link: node.href });
        } catch (labels_error) {
        }
    }

    return res;
}

function checkMessagesCount() {
    var indicators = [];

    try {
        var inboxNode = validatedNode(interestNodes.inbox);
        if (inboxNode === null) {
            return indicators;
        }

        indicators.push({ name: _("Inbox"),
                          count: validatedNodeValue(interestNodes.inbox, inboxNode),
                          callback: makeRedirector(inboxNode.href) });

        var i, labels = getLabels();
        for (i = 0; i < labels.length; i++) {
            indicators.push({ name: trim(labels[i].name), count: labels[i].count, callback: makeRedirector(labels[i].link) });
        }

    } catch (messages_error) {
    }

    return indicators;
}

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

    reportTestState('PASS SELF TEST');
}

function isCorrectPage() {
    var i, ids = ['hist_frame', 'js_frame'];

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

    return true;
}

function doMatrixIntegration() {
    doMainMenuIntegration(document);

    var i, labels = getLabels();
    for (i = 0; i < labels.length; i++) {
        Unity.addAction('/' + labels[i].name, makeRedirector(labels[i].link));
    }
}

function unityLoaded() {
    var composeNewMessage = wrapCallback(function () {
        var compose = getComposeMessageNode();
        click(compose);
    });

    Unity.MessagingIndicator.addAction(_("Compose New Message"),
                                       composeNewMessage);
    Unity.Launcher.addAction(_("Compose New Message"),
                             composeNewMessage);

    var indicatorsController = new Indicators(checkMessagesCount);

    window.onpopstate = function () {
        var hash = window.location.hash;
        var label = null;
        if (hash.match(/#label\/(.+)/)) {
            label = unescape(hash.match(/#label\/(.+)/)[1]);
        } else if (hash === '#inbox') {
            label = _("Inbox");
        } else {
            return;
        }
        indicatorsController.visited(label);
    };

    doMatrixIntegration();

    selfTest();
}


if (isCorrectPage()) {
    setTimeout(wrapCallback(function wait() {
        var pane = validatedNode(interestNodes.pane);

        if (!pane || !document.getElementsByClassName("nU")) {
            setTimeout(wait, 1000);
            return;
        }
        var login = null;
        try {
            var loginNode = validatedNode(interestNodes.login);
            if (loginNode !== null) {
                login = loginNode.textContent;
            }
        } catch (gmail_err) {
        }

        Unity.init({ name: "Gmail",
                     login: login,
                     iconUrl: "icon://unity-webapps-gmail",
                     homepage: 'https://mail.google.com',
                     domain: 'mail.google.com',
                     onInit: wrapCallback(unityLoaded) });
    }), 2000);
}
