var request = require("request");
var throttledRequest = require('throttled-request')(request);
throttledRequest.configure({ requests: 8, milliseconds: 60000 }); //send 1 request per second
cachedRequest = require('cached-request')(throttledRequest);
cachedRequest.setCacheDirectory("./cache");
var emoji = require('node-emoji')
module.exports = {
    football_today: async (bot, msg, logger) => {
        logger.info("ID - " + msg.from.id + " First Name - " + msg.from.first_name + " asked for football today");
        var options = {
            method: 'GET',
            url: 'https://football-pro.p.rapidapi.com/api/v2.0/livescores',
            qs: { tz: 'Europe/London', leagues: '2,5,8,23,501,732,1326', include: 'localTeam,visitorTeam' }, // Champions Leage, Europa, Premier League, Community Shield, Scottish
            headers: {
                'x-rapidapi-host': 'football-pro.p.rapidapi.com',
                'x-rapidapi-key': process.env.RAPIDAPI_API_KEY,
                useQueryString: true
            },
            ttl: 18000000 //5 hours
        };
        cachedRequest(options, async function (error, response, body) {
            if (error) throw new Error(error);
            let jsonBody = JSON.parse(body)
            if (jsonBody.data.length > 0) {
                bot.sendMessage(msg.chat.id, 'Yes there is!').then(async () => {
                    for (const x of jsonBody.data) {
                        var homeTeam = x.localTeam.data.name
                        var awayTeam = x.visitorTeam.data.name
                        var startTime = x.time.starting_at.time
                        await bot.sendMessage(msg.chat.id, homeTeam + " VS " + awayTeam + " @ " + startTime)
                    }
                }).then(() => {
                    return bot.sendMessage(msg.chat.id, `To see what channels the football is streaming on goto post ${emoji.get('one')}${emoji.get('six')} in our updates page and join our football listings rooms.\n\n${emoji.get('arrow_right')}PRESS HERE${emoji.get('arrow_left')} to go directly to post in updates page.`, { parse_mode: 'HTML', disable_web_page_preview: true })
                })
            } else {
                bot.sendMessage(msg.chat.id, `Sadly, there is no football I care about on today ${emoji.get('cry')} but, Updates ${emoji.get('one')}${emoji.get('six')} HERE also has telegram rooms for all other sports.`, { parse_mode: 'HTML', disable_web_page_preview: true })
            }
        })
    },
    // get_all_pages: async () => {
    //     full_list = []
    //     pages = [1,2,3,4,5]
    //     for (let i = 1; i < pages.length; i++) {
    //         var options = {
    //             method: 'GET',
    //             url: 'https://api.themoviedb.org/3/tv/airing_today?api_key=01fe1ed0ba2275d4a9ce618fbabdac92&language=en-GB&page=' + i,
    //             ttl: 18000000 //5 hours
    //         };
    //         return new Promise(function (resolve, reject) {
    //             request(options, function (error, response, body) {
    //                 if (!error) {
    //                     // resolve(body);
    //                     full_list.push(JSON.parse(body))
    //                     resolve(full_list[0])
    //                 } else {
    //                     reject(error);
    //                 }
    //             })
    //         })
    //       } 
    // },
    api_call: async (currentPage) => {
        var options = {
            method: 'GET',
            url: 'https://api.themoviedb.org/3/tv/airing_today?api_key=01fe1ed0ba2275d4a9ce618fbabdac92&language=en-GB&page=' + currentPage,
            ttl: 18000000 //5 hours
        };
        return new Promise(function (resolve, reject) {
        request(options, function (error, response, body) {
            if (!error) {
                resolve(JSON.parse(body))
            } else {
                reject(error);
            }
        })
    })
    },
    get_all_pages: async () => {
        let currentPage = 1;
        full_list = []
        while (currentPage <= 5) {
            a = await module.exports.api_call(currentPage);
            // let { data } = await module.exports.api_call(currentPage);
            full_list.push(a.results)
            currentPage++;
        }
        a = Array.prototype.concat.apply([], full_list)
        return a
    },
    tv_today: async (bot, msg, logger) => {
        logger.info("ID - " + msg.from.id + " First Name - " + msg.from.first_name + " asked for tv today");
        l = await module.exports.get_all_pages()
        if (l.length > 0) {
            bot.sendMessage(msg.chat.id, 'Yes there is!').then(async () => {
                a = []
                b = l.filter(s => { return s.origin_country[0] == 'GB' || s.origin_country[0] == 'US' })
                for (const x of b) {
                    var showName = x.name
                    a.push(showName)
                }
                new_ms = a.join('\n')
                await bot.sendMessage(msg.chat.id, new_ms, { parse_mode: "HTML" })
            }).then(() => {
                return bot.sendMessage(msg.chat.id, `Enjoy your TV Shows today!.`, { parse_mode: 'HTML', disable_web_page_preview: true })
            })
        } else {
            bot.sendMessage(msg.chat.id, `Sadly, there is no tv shows on I care about on today ${emoji.get('cry')}.`, { parse_mode: 'HTML', disable_web_page_preview: true })
        }
    }
    // bot.sendMessage(msg.chat.id, jsonBody.content)
}