// ==UserScript==
// @include       https://plus.google.com/*
// @require       utils.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 isCorrectPage() {
    var i, ids = ['contentPane'];

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

    return true;
}

function getNodeOr(candidateXPaths, parent, xpathType, getValueFunc) {
    var value;
    var found;
    var i;

    for (i = 0; i < candidateXPaths.length; ++i) {
        found = document.evaluate(candidateXPaths[i],
                                  parent, null, xpathType, null);
        if (found) {
            value = getValueFunc(found);
            if (value) {
                break;
            }
        }
    }
    return value;
}

function getPosts() {
    var container = document.getElementById('contentPane');
    var unreadItems = getNodeOr(['//div[@guidedhelpid="streamcontent"]/div/div/div/div[contains(@id,"update-")]'],
                                container,
                                XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
                                function (found) { return found.snapshotLength !== 0 ? found : null; });

    unreadItems = unreadItems || [];

    function find_icon() {
        return function (found) {
            return (found.singleNodeValue && found.singleNodeValue.src) ? found : null;
        };
    }

    function find_text() {
        return function (found) {
            return (found.singleNodeValue && found.singleNodeValue.textContent) ? found : null;
        };
    }

    var i, node, icon, author, body, res = [], bodyNode;
    for (i = 0; i < unreadItems.snapshotLength; i++) {
        node = unreadItems.snapshotItem(i);

        icon = getNodeOr(
            ['div/div/div/div/a/img', 'div/div/div/a/img'],
            node,
            XPathResult.ANY_UNORDERED_NODE_TYPE,
            find_icon()
        ).singleNodeValue.src;

        author = getNodeOr(
            ['div/div/div/div/div/header/h3/a', 'div/div/div/div/header/h3/a'],
            node,
            XPathResult.ANY_UNORDERED_NODE_TYPE,
            find_text()
        ).singleNodeValue.textContent;

        bodyNode = getNodeOr(
            ['div[2]/div/div[2]/div/div/div/div[2]'],
            node,
            XPathResult.ANY_UNORDERED_NODE_TYPE,
            find_text()
        );
        if (bodyNode) {
            body = bodyNode.singleNodeValue.textContent;

            res.push({ icon: icon,
                       author: author,
                       body: body });
        }
    }
    return res;
}

function selfTest() {
    var i, readItems = getPosts();

    if (!readItems.length) {
        return;
    }

    for (i = 0; i < readItems.length; i++) {
        if (!readItems[i].icon || !readItems[i].author) {
            return;
        }
    }

    reportTestState('PASS SELF TEST');
}

function markAsRead(items) {
    var i;
    for (i = 0; i < items.length; i++) {
        if (items[i].body) {
            localStorage.setItem(items[i].body, true);
        }
    }
}

function filterReaded(items) {
    return items.filter(function (item) {
        return item.body && !localStorage.getItem(item.body);
    });
}

function showItems(items) {
    var i;
    for (i = 0; i < items.length; i++) {
        localStorage.setItem(items[i].body, true);
        Unity.Notification.showNotification(items[i].author, items[i].body, items[i].icon);
    }
}

function messagingIndicatorSetup() {
    var tabActive = true;

    window.onblur = function () {
        tabActive = false;
    };
    window.onfocus = function () {
        tabActive = true;
    };

    var checkMessagesCount = wrapCallback(function () {
        var i, unreadItems = filterReaded(getPosts());

        if (tabActive) {
            markAsRead(unreadItems);
        } else {
            showItems(unreadItems);
        }
    });

    checkMessagesCount();
    setInterval(checkMessagesCount, 1000);

    doMainMenuIntegration(document);

    selfTest();
}

function getAppNameNode() {
    return document.evaluate('//div[@id="contentPane"]/div/div/div/div/div[3]',
                             document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
}

function getImg(appName) {
    var params = "numNotificationsToFetch=20&sp=%5B9%2C2%2Cnull%2Cnull%2Cnull%2C20%2Cnull%2Cnull%2C%5B%5D%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2Cnull%2C%5B%5D%5D&at=AObGSAhjSyZGNGIsEddNiQgGm1C9qNxXuQ%3A1350006133009&";
    var request = new XMLHttpRequest();

    request.onreadystatechange = wrapCallback(function () {
        if (request.readyState === 4) {
            var text = request.responseText;
            var pos = text.indexOf(appName);
            while (text[pos] !== '[' && pos > 0) {
                pos--;
            }
            var startPos = pos;
            pos++;
            var depth;
            for (depth = 1; depth && pos < text.length; pos++) {
                if (text[pos] === '[') {
                    depth++;
                }
                if (text[pos] === ']') {
                    depth--;
                }
            }
            var desc = text.substr(startPos, pos - startPos);

            pos = desc.indexOf(',');
            while (desc.indexOf(',', pos + 1) !== -1) {
                pos = desc.indexOf(',', pos + 1);
            }

            var img = desc.substr(pos + 2);
            img = img.substr(0, img.length - 2);
            if (img.indexOf('https://') !== -1) {
                img = 'http://' + img.substr('https://'.length);
            }
            Unity.init({ name: appName,
                         iconUrl: img,
                         crop: true,
                         domain: 'plus.google.com',
                         force: true,
                         homepage: String(window.location),
                         onInit: function () {} });
        }
    });
    request.open("POST", "https://plus.google.com/u/0/_/games/getGamesModel?hl=en&ozv=es_oz_20121009.17_p3&avw=ggs%3A2&_reqid=820537&rt=j", true);

    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");

    request.send(params);
}

if (isCorrectPage() && !unsafeWindow._alreadyOnPage) {
    var previous = '';
    unsafeWindow._alreadyOnPage = true;
    /* TODO: uncomment after lp:~zaspire/unity-firefox-extension/context-reinitialization merged
    setInterval(wrapCallback(function wait() {
        // It's change location without reloading page
        if (!getAppNameNode() || !getAppNameNode().textContent.length) {
            return;
        }
        var appName = getAppNameNode().textContent;
        if (previous == appName)
            return;
        previous = appName;
        getImg(appName);
        localStorage.setItem(appName, true);
    }), 2000);*/
    Unity.init({ name: "GooglePlus",
                 domain: 'plus.google.com',
                 homepage: 'https://plus.google.com/',
                 iconUrl: "icon://unity-webapps-google-plus",
                 onInit: wrapCallback(messagingIndicatorSetup) });
}
