// ==UserScript==
// @include       http://vk.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"
));

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

function isCorrectPage() {
    var i, ids = ['top_links', 'logout_link'];

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

    return true;
}

function playerSetup() {
    // Chromium: This function is being injected into the webpage e.g. in a different
    // JS context than the content script's. You cannot close over content script variables.
    Unity = window.Unity || external.getUnityObject(1);

    var audioPlayer = window.audioPlayer;
    if (!audioPlayer) {
        return;
    }
    if (audioPlayer.player) {
        if (!audioPlayer.player.paused()) {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
        } else {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
        }
    }

    Unity.MediaPlayer.onPlayPause(function () {
        if (audioPlayer.player.paused()) {
            audioPlayer.playTrack();
        } else {
            audioPlayer.pauseTrack();
        }
    });

    Unity.MediaPlayer.setTrack({
        title: audioPlayer.lastSong[6],
        album: null,
        artist: audioPlayer.lastSong[5],
        artLocation: null
    });

    Unity.MediaPlayer.onNext(function () {
        audioPlayer.nextTrack();
    });

    Unity.MediaPlayer.onPrevious(function () {
        audioPlayer.prevTrack();
    });
}

function messagingIndicatorSetup() {
    var countElement = document.evaluate('//li[@id="l_msg"]/a/span[2]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue;
    function checkMessagesCount() {
        var count = countElement.textContent;
        if (!count.length) {
            count = '0';
        }

        Unity.MessagingIndicator.showIndicator(_("Inbox"), { count: count });
    }

    countElement.addEventListener('DOMSubtreeModified', checkMessagesCount, false);

    checkMessagesCount();

    evalInPageContext('function () {setInterval(' + playerSetup + ', 1000);}');
}

if (isCorrectPage()) {
    Unity.init({ name: _("vk.com"),
                 domain: 'vk.com',
                 homepage: 'http://vk.com',
                 iconUrl: 'icon://unity-webapps-vkontakte-ru',
                 onInit: messagingIndicatorSetup });
}
