"use strict";
module.exports = function (spotify, queue, playlist) {
  var firebase = require("./firebase");
  var firebaseStatus = firebase.ref.child("player/playing");
  var firebaseNext = firebase.ref.child("player/next");

  firebaseStatus.on("value", function(data){
    console.log("Status updated", data.val());
    if (data.val() === true) {
      play();
    } else if (data.val() === false) {
      pause();
    }
  });
  firebaseNext.on("value", function(data){
    console.log("Next updated", data.val());
    if (data.val() === true) {
      playNext();
      firebaseNext.set(false);
    }
  });

  function start(){
    console.log("Starting player");

    currentTrack();

    spotify.player.on({
        endOfTrack: playNext
    });

    playNext();
  }

  function playNext(){
    var track = nextTrack();
    if (track) {
      console.log("Playing track:", track.artists(), "-", track.title());
      spotify.player.play(track.getLink());
      firebaseStatus.set(true);
      currentTrack(track);
    } else {
      console.log("No track to play. Trying again in 1 second");
      spotify.player.pause();
      setTimeout(playNext, 1000);
    }
  }

  function play(){
    console.log("Player play");
    firebaseStatus.set(true);
    spotify.player.resume();
  }

  function pause(){
    console.log("Player pause");
    firebaseStatus.set(false);
    spotify.player.pause();
  }

  function nextTrack(){
    return queue.next() || playlist.next();
  }

  function currentTrack(track){
    if (track) {
      firebase.currentTrack(track.json());
    } else {
      firebase.currentTrack({});
    }
  }

  return {
    start: start,
    play: play,
    pause: pause,
    next: playNext,
    queue: queue,
    playlist: playlist
  };
};

@@ -218,16 +218,84 @@
 /next%22);
+%0A  var firebaseCurrent = firebase.ref.child(%22player/current_track%22);
 %0A%0A  fire
@@ -1604,34 +1604,29 @@
 base
-.c
+C
 urrent
-Track
+.set
 (track.
-json()
+uri
 );%0A 
@@ -1655,24 +1655,24 @@
 base
-.c
+C
 urrent
-Track(%7B%7D
+.set(null
 );%0A 

Set Current track