// ==UserScript==
// @include     http://*.deezer.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.0);
window.Unity = Unity;
var trackInfo;

if (typeof unsafeWindow === "undefined") {
    unsafeWindow = evalInPageContext(function () {
        return window;
    });
}
unsafeWindow.Unity = window.Unity;

function log(txt) {
    if (typeof (console) !== 'undefined' && typeof (console.log) !== 'undefined') {
        console.log(txt);
    }
}

function isCorrectPage() {
    var i, ids = ['h_previous', 'h_next', 'h_play'];
    if (!unsafeWindow.dzPlayer) {
        log("deezer not valid. unsafeWindow");

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

    return true;
}


function getTrackInfo() {
    var artist = null;
    var title = document.title;
    var artLocation = null;
    var album = null;
    try {
        artist = unsafeWindow.dzPlayer.artistName;
        title = unsafeWindow.dzPlayer.songTitle;
        album = unsafeWindow.dzPlayer.albumTitle;
        artLocation = unsafeWindow.SETTING_DOMAIN_IMG + '/cover/' + ((typeof (unsafeWindow.dzPlayer) === 'undefined') ? '' : unsafeWindow.dzPlayer.cover) + '/315x315-000000-80-0-0.jpg';
    } catch (x) {
        log(x);
    }


    return {
        title: title,
        album: album,
        artist: artist,
        artLocation: artLocation
    };

}

function refreshInfos() {

    //track info
    var oldTrackInfo;
    if (trackInfo) {
        oldTrackInfo = trackInfo;
    }
    trackInfo = getTrackInfo();
    if (oldTrackInfo) {
        if (oldTrackInfo.artist !== trackInfo.artist || oldTrackInfo.title !== trackInfo.title) {
            Unity.Notification.showNotification(trackInfo.title, trackInfo.artist, trackInfo.artLocation);
        }
    }
    Unity.MediaPlayer.setTrack(trackInfo);

    if (!trackInfo) {
        return;
    }

    // play pause button
    if (unsafeWindow.dzPlayer.isPlaying()) {
        Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
    } else {
        Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
    }

    //indicator : current track percent and number of tracks in the playlist
    Unity.Launcher.setCount(unsafeWindow.dzPlayer.getNbSongs() - unsafeWindow.dzPlayer.getNumSong());
    if (unsafeWindow.dzPlayer.isPlaying()) {
        Unity.Launcher.setProgress(unsafeWindow.dzPlayer.getPosition() /  unsafeWindow.dzPlayer.getDuration());
    } else {
        Unity.Launcher.clearProgress();
    }

}

// function waitAndPopulateUserInfos() {
    // if (unsafeWindow.userData && unsafeWindow.userData.data && unsafeWindow.userData.data.FAVORITES_ALBUMS.data) {
        // log("here");

        // populateUserInfos();

    // }
    // else {
    //     log("wait for user info.");
    //     setTimeout(wrapCallback(waitAndPopulateUserInfos),100);
    // }
// }

function playAlbumCallback(id) {
    return wrapCallback(function () {
        unsafeWindow.dzPlayer.playAlbum(id);
    });
}

function playPlaylistCallback(id) {
    return wrapCallback(function () {
        unsafeWindow.dzPlayer.playPlaylist(id);
    });
}

function populateUserInfos() {
    //put favorite album in the HUD
    var datas = unsafeWindow.userData.data.FAVORITES_ALBUMS.data;
    var current;
    var i;

    log("populating user infos");

    for (i = datas.length - 1; i >= 0; i--) {
        current = datas[i];
        Unity.addAction("/Album/Play/" + current.ALB_TITLE + " - " + current.ART_NAME,
            playAlbumCallback(current.ALB_ID));
        log("added");
                // Unity.addAction("/Album/View/" + current.ALB_TITLE + " - " + current.ART_NAME,
            // playAlbumCallback(current.ALB_ID))
    }

    //playlist favorite (not actual user playlist)
    datas = unsafeWindow.userData.data.FAVORITES_PLAYLISTS.data;
    for (i = datas.length - 1; i >= 0; i--) {
        current = datas[i];
        Unity.addAction("/Playlist/Play/" + current.TITLE,
            playPlaylistCallback(current.PLAYLIST_ID));
    }
}

function selfTest() {
    if (!unsafeWindow.dzPlayer) {
        reportTestState('FAILED: dzPlayer is null');
    }
    if (!unsafeWindow.userData) {
        reportTestState('FAILED: userData is null');
    }

    reportTestState('PASS SELF TEST');
}

function musicPlayerSetup() {
    log("start init deezer");

    Unity.MediaPlayer.init("Deezer");

    if (!isCorrectPage()) {
        return;
    }

    setInterval(wrapCallback(function retry() {
        if (!isCorrectPage()) {
            return;
        }
        refreshInfos();

    }), 1000);


    Unity.MediaPlayer.onPlayPause(wrapCallback(function () {
        if (!unsafeWindow.dzPlayer.isPlaying()) {
            unsafeWindow.playercontrol.doAction('play');
            //I don't like the little delay before the button updates.
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PLAYING);
        } else {
            unsafeWindow.playercontrol.doAction('pause');
            Unity.MediaPlayer.setPlaybackState(Unity.MediaPlayer.PlaybackState.PAUSED);
        }
    }));

    Unity.MediaPlayer.onNext(wrapCallback(function () {
        unsafeWindow.playercontrol.doAction('next');
    }));

    Unity.MediaPlayer.onPrevious(wrapCallback(function () {
        unsafeWindow.playercontrol.doAction('prev');
    }));

    //user infos
    // TODO disable because addAction does not seem to work atm
    // populateUserInfos();

    selfTest();
    log("end of init");

}

Unity.init({
    name: "Deezer",
    domain: 'deezer.com',
    homepage: 'http://deezer.com',
    iconUrl: "icon://unity-webapps-deezer",
    onInit: musicPlayerSetup
});
