var Tone = require('tone');
var log = require('./log');

function SoundPlayer () {
    this.outputNode;
    this.buffer; // a Tone.Buffer
    this.bufferSource;
    this.playbackRate = 1;
    this.isPlaying = false;
}
SoundPlayer.prototype.connect = function (node) {
    this.outputNode = node;
};

SoundPlayer.prototype.setBuffer = function (buffer) {
    this.buffer = buffer;
};

SoundPlayer.prototype.setPlaybackRate = function (playbackRate) {
    this.playbackRate = playbackRate;
    if (this.bufferSource && this.bufferSource.playbackRate) {
        this.bufferSource.playbackRate.value = this.playbackRate;
    }
};

SoundPlayer.prototype.stop = function () {
    if (this.isPlaying){
        this.bufferSource.stop();
    }
};

SoundPlayer.prototype.start = function () {
    if (!this.buffer || !this.buffer.loaded) {
        log.warn('tried to play a sound that was not loaded yet');
        return;
    }

    this.stop();

    this.bufferSource = new Tone.BufferSource(this.buffer.get());
    this.bufferSource.playbackRate.value = this.playbackRate;
    this.bufferSource.connect(this.outputNode);
    this.bufferSource.start();
    this.isPlaying = true;
};

SoundPlayer.prototype.onEnded = function (callback) {
    this.bufferSource.onended = function () {
        this.isPlaying = false;
        callback();
    };
};

module.exports = SoundPlayer;

@@ -185,36 +185,8 @@
  1;%0A
-    this.isPlaying = false;%0A
 %7D%0ASo
@@ -652,18 +652,22 @@
 his.
-isPlaying)
+bufferSource) 
 %7B%0A  
@@ -893,26 +893,8 @@
  %7D%0A%0A
-    this.stop();%0A%0A
     
@@ -1100,35 +1100,8 @@
 ();%0A
-    this.isPlaying = true;%0A
 %7D;%0A%0A
@@ -1126,13 +1126,14 @@
 ype.
-onEnd
+finish
 ed =
@@ -1147,28 +1147,107 @@
 on (
-callback) %7B%0A    this
+) %7B%0A    var storedContext = this;%0A    return new Promise(function (resolve) %7B%0A        storedContext
 .buf
@@ -1292,57 +1292,40 @@
     
-this.isPlaying = false;%0A        callback()
+    resolve();%0A        %7D
 ;%0A    %7D
+)
 ;%0A%7D;

use promise on playback finished