'use strict';

const playPause = require('./playpause');
const commonFunctions = require('./commonFunctions');
const Promise = require('bluebird');
const favourites = require('../helpers/favourites');
const debug = require('debug')('helpers:favourite');

function playFavourite(player, requestedFavourite, timeout) {
    let trackChanged;
    const promiseTimeout = timeout || 30000;

    function onTransportStateChange(status) {
        debug(`status changed in onTransportStateChange ${commonFunctions.returnFullObject(status)}`);
        if (trackChanged instanceof Function) {
            trackChanged();
        }
    }

    return Promise.resolve()
        .then(() => {
            return favourites.getFavourite(player, requestedFavourite);
        })
        .then((results) => {
            if (results) {
                debug('calling playPause.pause()');

                return playPause.pause(player);
            }
            throw new Error('favourite not found');
        })
        .then(() => {
            debug('calling player.coordinator.replaceWithFavorite()');
            player.on('transport-state', onTransportStateChange);

            return player.coordinator.replaceWithFavorite(requestedFavourite);
        })
        .then(() => {
            debug('waiting for state change');

            return new Promise((resolve) => {
                trackChanged = resolve;
            });
        })
        .timeout(promiseTimeout)
        .then(() => {
            debug('calling playPause.play()');

            return playPause.play(player);
        })
        .catch(Promise.TimeoutError, (error) => {
            throw new Error(`timeout waiting for state change : ${error}`);
        })
        .catch((error) => {
            debug(`error in playFavourite() :  ${commonFunctions.returnFullObject(error)}`);
            throw error;
        })
        .finally(() => {
            player.removeListener('transport-state', onTransportStateChange);
        });
}

module.exports = {
    playFavourite
};

@@ -376,16 +376,40 @@
 %7C 30000;
+%0A    let sonosFavourite;
 %0A%0A    fu
@@ -830,24 +830,66 @@
 (results) %7B%0A
+                sonosFavourite = results;%0A
             
@@ -1068,32 +1068,221 @@
   .then(() =%3E %7B%0A
+            if (player.state.currentTrack.uri === sonosFavourite.uri) %7B%0A                debug('same stream as currently playing');%0A%0A                return 'no stream change';%0A            %7D%0A
             debu
@@ -1500,39 +1500,98 @@
 %0A        .then((
+result
 ) =%3E %7B%0A
+            if (result !== 'no stream change') %7B%0A    
             debu
@@ -1618,24 +1618,28 @@
  change');%0A%0A
+    
             
@@ -1680,32 +1680,36 @@
                 
+    
 trackChanged = r
@@ -1728,20 +1728,64 @@
         
+   
+ 
 %7D);%0A
+            %7D%0A%0A            return true;%0A
         

make playfavourite work when playing same stream