// ==UserScript==
// @include       http://music.yandex.ru/*
// @include       https://music.yandex.ru/*
// @require       utils.js
// ==/UserScript==

window.Unity = external.getUnityObject(1);

function isCorrectPage() {
    if (!document.getElementsByClassName('b-head-logo__legal')[0]) {
        return false;
    }

    return true;
}

function getTrackInfo() {
    var artist = document.getElementsByClassName('b-link js-player-artist')[0].textContent;
    var artLocation = document.getElementsByClassName('b-jambox__cover js-player-cover')[0].src;
    var title = document.getElementsByClassName('b-link js-player-title')[0].textContent;

    var trackInfo = {
        title: title,
        album: null,
        artist: artist,
        artLocation: artLocation
    };
    return trackInfo;
}

function musicPlayerSetup() {
    Unity.MediaPlayer.init(_("Yandex Music"));

    setInterval(function () {
        Unity.MediaPlayer.setTrack(getTrackInfo());
    }, 3000);

    setInterval(function () {
	var paused = document.evaluate('//div[@class="l-dpage__wrapper"]/div[@id="js-head"]/div/div/div/div[contains(@class, "b-jambox js-player")]', document, null, XPathResult.ANY_UNORDERED_NODE_TYPE, null).singleNodeValue.className.match(/js-player-paused/);
        if (paused) {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
        } else {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
        }
    }, 500);

    Unity.MediaPlayer.onPlayPause(function () {
        var node = document.getElementsByClassName('b-jambox__play__i')[0];
        launchClickEvent(node);
    });

    Unity.MediaPlayer.onNext(function () {
        var node = document.getElementsByClassName('b-jambox__button b-jambox__button_type_next js-player-next')[0];
        launchClickEvent(node);
    });

    Unity.MediaPlayer.onPrevious(function () {
        var node = document.getElementsByClassName('b-jambox__button b-jambox__button_type_prev js-player-prev')[0];
        launchClickEvent(node);
    });
}

if (isCorrectPage()) {
    Unity.init({ name: _("Yandex Music"),
		 domain: 'music.yandex.ru',
		 homepage: 'http://music.yandex.ru/',
                 iconUrl: "icon://unity-webapps-yandex-music",
                 onInit: musicPlayerSetup });
}
