# Description:
#   utilità per il meteo
#
# Dependencies:
#   "moment":"2.10.2"
#
# Configuration:
#   WEATHER_API_KEY
#
# Commands:
#   hubot meteo/che tempo fa/c'è a <luogo>? - ottieni il meteo
# 
# Author:
#   Enrico Fasoli (fazo96)
#   Michele Guerini Rocco (rnhmjoj)

moment = require 'moment'

regex = /(?:(?:d(?:a|i)mmi il )?meteo(?: per (.+))?|che tempo (?:fa|c'è)(?: (?:a|in) (.+))?)\??$/i

url1 = 'http://ip-api.com/json/'
url2 = 'http://api.openweathermap.org/data/2.5/weather?lang=it&units=metric'

err1 = 'non so dove sono: chiedimi un posto in particolare'
err2 = 'errore nel guardare il cielo'

module.exports = (robot) ->
  get_location = (callback) ->
    robot.http(url1).get() (err, r, body) ->
      try
        city = JSON.parse(body).city
      catch e
        # Fallback
        callback 'Crema'
        return
      if err or !city? or city is undefined
        # Fallback
        callback 'Crema'
        return
      callback city

  get_weather = (query, callback) ->
    key = process.env.WEATHER_API_KEY
    if not key
      return callback 'non ho la chiave per openweathermap :('
    robot.http(url2 + '&appid='+key + '&q='+query).get() (err, r, body) ->
      callback err, body

  send_weather = (res) -> (err, body) ->
    return res.send "#{err2}:\n#{err}" if err
    try
      body = JSON.parse body
    catch e
      return res.send "#{err2}: #{e}"
    unless body?.sys? and body?.main? and body?.weather?.push?
      return res.send "#{err2}:\n#{JSON.stringify body}"

    dawn = (moment.unix body.sys.sunrise).format 'H:MM'
    dusk = (moment.unix body.sys.sunset ).format 'H:MM'

    res.send "meteo per #{body.name}:\n
      #{Math.round body.main.temp} °C, #{body.weather[0].description} con
      #{body.main.humidity}% di umidità. l'alba è alle #{dawn} mentre il
      tramonto alle #{dusk}"

  robot.respond regex, (res) ->
    city = res.match[1] || res.match[2]
    if city?
      get_weather city, send_weather res
    else
      get_location (location) ->
        get_weather location, send_weather res