/**
 * @file 意图处理类
 * @author yelvye@baidu.com
 */

let BaseBot = require('./../../lib/Bot');
const request = require('request');

const url = 'https://c.m.163.com/reader/api/motif/hotAll/list?motifId=HT1547607798713&refreshType=2&cursor=&ua=NewsApp/53.0%20iOS/11.4.1%20(iPhone7,2)';

const StandardCard = BaseBot.Card.StandardCard;

var getData = function(){
    return new Promise(function(resolve, reject){
        request({
            url: url
        }, function(error, res, body){
            var data = JSON.parse(body);
            if(data.code == 200) {
                resolve(data);
            }else{
                reject();
            }
        });
    });
}

var getResponse = function(){
    return new Promise(function(resolve, reject){
        getData().then(function(data){
            data = data.data;
            let index = Math.floor((Math.random()*data.length));
            let text = data[index].title;

            let card = new StandardCard();

            card.setTitle('冷知识');
            card.setContent(text);

            if(data[index].images && data[index].images.length){
                card.setImage(data[index].images[0].url);
            }

            resolve({
                "card": card,
                "outputSpeech": text
            });
        }, function(){
            reject({
                "outputSpeech":"数据获取失败"
            });
        });
    });
}

//console.log(BaseBot);

class Bot extends BaseBot {
    constructor(postData) {
        super(postData);


        this.addLaunchHandler(() => {
            this.waitAnswer();
            this.setExpectSpeech(false);
            
            return getResponse();
        });

        this.addSessionEndedHandler(() => {
            this.endSession();
            return {
                outputSpeech: '感谢您的使用'
            };
        });

        this.addIntentHandler('ai.dueros.common.next_intent', () => {
            return getResponse();
        });

    }
}

module.exports = Bot;
