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

window.Unity = external.getUnityObject(1);

function isCorrectPage() {
    var i, ids = ['interface', 'audio'];

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

    return true;
}

function musicPlayerSetup() {
    function getTrackInfo() {
        var trackInfo = {
            title: null,
            artist: null,
            album: null,
            artLocation: null
        };

        try {
            trackInfo.title = document.getElementById('trackname').textContent;
            trackInfo.artist = document.getElementById('artistname').textContent;
        } catch (x) {}
        return trackInfo;
    }

    function changeState(dryRun) {
        var isPlaying = true;
        var button = document.getElementById('play');
        if (document.getElementById('play').style.display !== "none") {
            isPlaying = false;
            button = document.getElementById('pause');
        }

        if (!dryRun) {
            launchClickEvent(button);
            isPlaying = !isPlaying;
        }

        if (isPlaying) {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
        } else {
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
        }
    }
    Unity.MediaPlayer.init("Libre.fm");

    Unity.MediaPlayer.onPlayPause(function () {
        changeState();
    });

    Unity.MediaPlayer.onNext(function () {
        launchClickEvent(document.getElementById("skipforward"));
    });

    Unity.MediaPlayer.onPrevious(function () {
        launchClickEvent(document.getElementById("skipback"));
    });

    setInterval(wrapCallback(function () {
        changeState(true);
        Unity.MediaPlayer.setTrack(getTrackInfo());
    }), 1000);
}

if (isCorrectPage()) {
    Unity.init({
        name: "Libre.fm",
        iconUrl: 'http://upload.wikimedia.org/wikipedia/en/9/97/Libre.fm_logo.svg',
        crop: true,
        domain: 'libre.fm',
        homepage: 'http://libre.fm',
        onInit: wrapCallback(musicPlayerSetup)
    });
}
