var Promise = require('promise') var requestPromise = require('./helpers/requestPromise.js') var BasePlugin = require('./base.js') var cheerio = require('cheerio') class Pwm extends BasePlugin { constructor (config) { super(config) this.name = 'Pvm' this.apikey = config.keys.owm.apiKey // owm for sunrise } help () { // | Command | Description return '.pvm Kertoo päivän, nimipäivän ja muita tietoja' } test (input) { var res = input.match(/^\.pvm$/i) if (res) { return true } return false } today () { var today = new Date() var month = today.getMonth() + 1 var day = today.getDate() var dateString = day + '.' + month + '.' return dateString } getWeather (city, code) { var language = 'fi' var urlArgs = { 'q': city, 'lang': language, 'APPID': this.apikey } var url = 'http://api.openweathermap.org/data/2.5/weather' var promise = requestPromise(url, urlArgs) return promise } getNimipaiva () { let dateString = this.today() var urlArgs = {} var url = 'http://nimipäivä.fi/' + dateString + '/' var promise = requestPromise(url, urlArgs, { 'Accept': 'application/json' }, true) return promise } getAllData () { return Promise.all([ this.getNimipaiva(), this.getWeather('Helsinki') ]) } result (input) { var that = this var resultPromise = new Promise(function (resolve, reject) { var res = input.match(/^\.pvm$/i) if (res) { that.getAllData().then(function (data) { // console.log(data) let weather = data[1] if (weather.cod === '404') { reject(new Error('Eioo')) return } let sunriseDate = new Date(Number(weather.sys.sunrise) * 1000) let sunsetDate = new Date(Number(weather.sys.sunset) * 1000) let sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes() let sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes() const $ = cheerio.load(data[0]) let names = [] $('.text p').children('a').each(function (i, elem) { names.push($(this).text()) }) let text = 'Pvm: Tänään on ' + that.today() + ' ja nimipäivää viettävät ' + names.join(', ') + '. Aurinko nousee ' + sunrise + ' ja laskee ' + sunset + '.' resolve(text) }, function (error) { reject(error) }) } }) return resultPromise } } module.exports = Pwm