// ==UserScript==
// @include       https://drive.google.com/*
// @include       https://docs.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"
));

var Unity = external.getUnityObject(1);
window.Unity = Unity;
unsafeWindow.Unity = window.Unity;

var menu = {};

var SUPPORTED_FORMATS = ['text/plain', 'application/vnd.oasis.opendocument.text', 'application/vnd.ms-word', 'application/pdf'];
unsafeWindow.SUPPORTED_FORMATS = SUPPORTED_FORMATS;

function getOffsetTop(node) {
    return node.offsetTop + (node.offsetParent ? getOffsetTop(node.offsetParent) : 0);
}

function getOffsetLeft(node) {
    return node.offsetLeft + (node.offsetParent ? getOffsetLeft(node.offsetParent) : 0);
}

function registerSubMenu(id, node) {
    var i, k, parent = document.getElementById(id).textContent;
    if (menu[id].childs.length) {
        return;
    }

    var res = document.evaluate('div[@class="goog-menuitem"]/div[@class="goog-menuitem-content"]',
                                node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var activateMenu = function () {
        click(this);
    };

    for (i = 0; i < res.snapshotLength; i++) {
        var item = res.snapshotItem(i);
        var textContent = '';

        for (k = 0; k < item.childNodes.length; k++) {
            if (item.childNodes[k].nodeName === '#text' || item.childNodes[k].className === 'goog-menuitem-mnemonic-hint'
                    || item.childNodes[k].nodeName === 'STRONG') {
                textContent += item.childNodes[k].textContent;
            }
        }

        if (textContent.length) {
            var path = '/' + parent + '/' + textContent;
            console.log(path);
            Unity.addAction(path, activateMenu.bind(item));
        }
    }
}

function registerMenu() {
    var matchMenuAndSubMenu = function () {
        var x, y, k;
        x = getOffsetLeft(this);
        y = getOffsetTop(this);

        if (!y) {
            return;
        }

        for (k in menu) {
            if (menu.hasOwnProperty(k) && menu[k].x === x && Math.abs(menu[k].y - y) < 40) {
                registerSubMenu(k, this);
                this.removeEventListener('DOMSubtreeModified', this._callback, false);
            }
        }
    };
    var i, elements = document.getElementsByClassName('goog-menu');

    if (!elements) {
        return;
    }

    for (i = 0; i < elements.length; i++) {
        var node = elements[i];
        if (!node._callback) {
            node._callback = matchMenuAndSubMenu.bind(node);
            node.addEventListener('DOMSubtreeModified', node._callback, false);
        }

    }
}

function doIntegration() {
    var matchMenuAndSubMenu = function () {
        var x, y, k;
        x = getOffsetLeft(this);
        y = getOffsetTop(this);

        if (!y) {
            return;
        }

        for (k in menu) {
            if (menu.hasOwnProperty(k) && menu[k].x === x && Math.abs(menu[k].y - y) < 40) {
                registerSubMenu(k, this);
                this.removeEventListener('DOMSubtreeModified', this._callback, false);
            }
        }
    };
    var i, node, elements = document.getElementsByClassName('menu-button goog-control goog-inline-block');

    for (i = 0; i < elements.length; i++) {
        node = elements[i];
        var x = getOffsetLeft(node);
        var y = getOffsetTop(node);
        menu[node.id] = { x: x, y: y, childs: [] };
    }

    var timeout = 10000;

    setTimeout(wrapCallback(function repeat() {
        registerMenu();
        var elements = document.getElementsByClassName('menu-button goog-control goog-inline-block');
        var i = 0;
        (function self() {
            if (i >= elements.length) {
                return;
            }
            click(elements[i]);
            matchMenuAndSubMenu.bind(elements[i])();
            click(elements[i]);
            i++;
            setTimeout(self, 100);
        }());
    }), timeout);

    if (document.getElementById('docs-title')) {
        var uri = window.location;
        uri = 'https://' + uri.hostname + uri.pathname + uri.search;
        linkVisited(uri, document.getElementById('docs-title').textContent);
    }

    doMainMenuIntegration(document);
}

Unity.init({ name: _("GoogleDocs"),
             domain: 'docs.google.com',
             homepage: 'https://docs.google.com/',
             mimeTypes: SUPPORTED_FORMATS.join(';') + ';',
             iconUrl: 'icon://unity-webapps-googledocs',
             onInit: wrapCallback(doIntegration) });

