const cheerio = require('cheerio')
    , fetch = require("node-fetch")
    , TimeAgo = require('javascript-time-ago') 
    , ko = require('javascript-time-ago/locale/ko')
    , fs = require('fs');

class Podbbang {

    constructor() {
        this.remotehost = 'http://192.168.6.63:8050/execute'
        TimeAgo.addLocale(ko)
        this.timeAgo = new TimeAgo('ko-KR')
    }

    getLatest(params) {
        return fetch(this.remotehost, {
            body: JSON.stringify(params),
            method: 'POST',
            timeout: 3000000,
            headers: {
                'content-type': 'application/json'
            }
        }).then(res => res.text()).then(async body => {
            // console.log($(".podcast-list li a.title").text())

            // fs.writeFile("podbbang.html", body, function (err) {
            //     if (err) {
            //         return console.log(err);
            //     }
            //     console.log("The file was saved!");
            // });
            let doc = cheerio.load(body)


            let data = []
            let studio = {}
            doc(".podcast-list li").map((k, v) => {
                studio = {}
                studio.Image = doc(v).find('.thumb img').attr('src')
                studio.Title = doc(v).find('.title').text()
                studio.Link = doc(v).find('.title').attr('href')
                studio.Description = doc(v).find('.description').text()
                studio.UpdatedAtStr = ((a) => {
                    studio.UpdatedAt = Date.now() - Math.abs(a) * 3600000
                    return this.timeAgo.format(studio.UpdatedAt)
                })(doc(v).find('.updated-at').text().match(/\d+/)[0] - 8)
                studio.Likes = doc(v).find('.likes dd').text()
                studio.Subscribes = doc(v).find('.subscribes dd').text()                
                data.push(studio)
            })
            // console.log(data)
            return data

        })
    }
}


module.exports = new Podbbang;