var alexa = require("alexa-app");
var search = require('youtube-search');
var fs = require('fs');
var request = require('request');

var app = new alexa.app("youtube");

var searchOpts = {
    maxResults: 1,
    type: 'video',
    key: process.env.YOUTUBE_API_KEY
};

var lastSearch;

app.pre = function(req, response, type) {
    if (req.applicationId !== process.env.ALEXA_APPLICATION_ID) {
        response.fail("Invalid application");
    }
};

app.intent("GetVideoIntent", {
        "slots": {
            "VideoQuery": "VIDEOS",
        },
        "utterances": [
            "search for {-|VideoQuery}",
            "find {-|VideoQuery}",
            "play {-|VideoQuery}",
            "start playing {-|VideoQuery}",
            "put on {-|VideoQuery}"
        ]
    },
    function(req, response) {
        var query = req.slot("VideoQuery");

        console.log('Searching ... ' + query);

        return new Promise((resolve, reject) => {
            search(query, searchOpts, function(err, results) {
                if (err) {
                    reject(err.message);
                } else if (results.length !== 1) {
                    resolve('I could not complete your request at this moment.', null, null);
                } else {
                    var metadata = results[0];
                    if (metadata.id === undefined) {
                        resolve(query + ' did not return any results on YouTube.', null, null);
                    } else {
                        console.log('Found ... ' + metadata.title);
                        var id = metadata.id;
                        var externalDownload = 'https://dmhacker-youtube.herokuapp.com/alexa/' + id;
                        request(externalDownload, function(err, res, body) {
                            console.log('Processed.');
                            if (err) {
                                reject(err.message);
                            } else {
                                recursive_check(id, 1000, function(err) {
                                    if (err) {
                                        reject(err.message);
                                    }
                                    else {
                                        lastSearch = JSON.parse(body).link;
                                        console.log('Stored @ '+lastSearch);
                                        resolve('I found a relevant video called ' + metadata.title + '.', lastSearch, metadata);
                                    }
                                });
                            }
                        });
                    }
                }
            });
        }).then(function (message, streamUrl, metadata) {
            response.say(message);
            if (streamUrl) {
                var stream = {
                    'url': streamUrl,
                    'token': metadata.id,
                    'offsetInMilliseconds': 0
                };
                response.audioPlayerPlayStream('REPLACE_ALL', stream);
                response.card({
                    'type': 'Simple',
                    'title': 'Search for "' + query + '"',
                    'content': 'Alexa found "' + metadata.title + '" at ' + metadata.link + '.'
                });
            }
            response.send();
        }).catch(function(reason) {
            response.fail(reason);
        });
    }
);

function recursive_check(id, delay, callback) {
    var linkCheck = 'https://dmhacker-youtube.herokuapp.com/alexa-check/' + id;
    request(linkCheck, function (err, res, body) {
        if (err) {
            callback(err);
        }
        else {
            var metadata = JSON.parse(body).metadata;
            if (!metadata) {
                callback(err);
            }
            else {
                if (metadata.downloaded) {
                    callback(null);
                }
                else {
                    setTimeout(function () {
                        recursive_check(id, delay, callback);
                    }, delay);
                }
            }
        }
    });
}

app.audioPlayer("PlaybackStarted", function(request, response) {
    console.log('Playback started.');
    console.log(request);
});

app.audioPlayer("PlaybackFailed", function(request, response) {
    console.log('Playback failed.');
    console.log(request);
});

app.intent("AMAZON.PauseIntent", {}, function(req, response) {
    response.audioPlayerStop();
});

app.intent("AMAZON.ResumeIntent", {}, function(req, response) {
    if (lastSearch === undefined) {
        response.say('You were not playing any video previously.');
    } else {
        response.audioPlayerPlayStream('ENQUEUE', {
            'url': lastSearch,
            'streamFormat': 'AUDIO_MPEG',
            'token': constants.token,
            'expectedPreviousToken': constants.expectedPreviousToken
        });
    }
});

app.intent("AMAZON.StopIntent", {}, function(req, response) {
    lastSearch = undefined;
    response.audioPlayerStop();
    response.audioPlayerClearQueue();
});

exports.handler = app.lambda();

@@ -1154,16 +1154,51 @@
 resolve(
+%7B%0A                        message: 
 'I could
@@ -1241,27 +1241,112 @@
 oment.',
- null, null
+%0A                        url: null,%0A                        metadata: null%0A                    %7D
 );%0A     
@@ -1497,16 +1497,55 @@
 resolve(
+%7B%0A                            message: 
 query + 
@@ -1590,19 +1590,116 @@
 e.',
- null, null
+%0A                            url: null,%0A                            metadata: null%0A                        %7D
 );%0A 
@@ -2666,16 +2666,71 @@
 resolve(
+%7B%0A                                            message: 
 'I found
@@ -2783,29 +2783,174 @@
 '.',
- lastSearch, metadata
+%0A                                            url: lastSearch,%0A                                            metadata: metadata%0A                                        %7D
 );%0A 
@@ -3166,39 +3166,147 @@
 on (
-message, streamUrl, metadata) %7B
+content) %7B%0A            var message = content.message;%0A            var streamUrl = content.url;%0A            var metadata = content.metadata;
 %0A   
@@ -3386,20 +3386,53 @@
     
-var stream =
+response.audioPlayerPlayStream('REPLACE_ALL',
  %7B%0A 
@@ -3577,78 +3577,8 @@
    %7D
-;%0A                response.audioPlayerPlayStream('REPLACE_ALL', stream
 );%0A 

resolve takes only one parameter