# -*- coding: utf-8 -*-

import json, time

import requests

from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
import GlobalStore


class Command(CommandTemplate):
	triggers = ['weather']
	helptext = "Gets the weather for the provided city"

	def execute(self, message):
		"""
		:type message: IrcMessage
		"""

		replytext = u""
		if not GlobalStore.commandhandler.apikeys.has_section("openweathermap") or not GlobalStore.commandhandler.apikeys.has_option("openweathermap", "key"):
			replytext = u"No API key for OpenWeatherMap found, please tell my owner so they can fix this"
		elif message.messagePartsLength == 0:
			replytext = u"Please enter the name of a city"
		else:
			params = {"APPID": GlobalStore.commandhandler.apikeys.get("openweathermap", "key"), "q": message.message, "units": "metric"}
			req = requests.get("http://api.openweathermap.org/data/2.5/weather", params=params)
			data = json.loads(req.text)
			if data['cod'] != 200:
				if data['cod'] == 404 or data['cod'] == '404':
					replytext = u"I'm sorry, I don't know where that is"
				else:
					replytext = u"An error occurred, please tell my owner to look at the debug output, or try again in a little while ({}: {})".format(data['cod'], data['message'])
					print "[weather] ERROR in API lookup:"
					print data
			else:
				#We've got data! Parse it
				#The highest wind angle where the direction applies
				windDirectionTranslation = {11.25: 'N', 33.75: 'NNE', 56.25: 'NE', 78.75: 'ENE', 101.25: 'E', 123.75: 'ESE',
											146.25: 'SE', 168.75: 'SSE', 191.25: 'S', 213.75: 'SSW', 236.25: 'SW',
											258.75: 'WSW', 281.25: 'W', 303.75: 'WNW', 326.25: 'NW', 348.75: 'NNW', 360.0: 'N'}
				windDirection = 'N'
				for maxDegrees in sorted(windDirectionTranslation.keys()):
					if data['wind']['deg'] < maxDegrees:
						break
					else:
						windDirection = windDirectionTranslation[maxDegrees]

				tempInFahrenheit = (data['main']['temp'] * 9 / 5) + 32

				dataAge = round((time.time() - data['dt']) / 60)
				replytext = u"{city} ({country}): {tempC:.2g}°C / {tempF:.3g}°F, {weatherType}. Wind: {windSpeed} m/s, {windDir}. Humidity of {humidity}% (Data is {dataAge:.0f} minutes old)"
				replytext = replytext.format(city=data['name'], country=data['sys']['country'], tempC=data['main']['temp'], tempF=tempInFahrenheit,
											 weatherType=data['weather'][0]['description'], windSpeed=data['wind']['speed'], windDir=windDirection,
											 humidity=data['main']['humidity'], dataAge=dataAge)

		message.bot.sendMessage(message.source, replytext)
@@ -2026,16 +2026,380 @@
 ) / 60)%0A
+%09%09%09%09dataAgeDisplay = u%22%22%0A%09%09%09%09if dataAge == 0:%0A%09%09%09%09%09dataAge = u%22brand new%22%0A%09%09%09%09else:%0A%09%09%09%09%09dataAgeDisplay = u%22%7BdataAge:.0f%7D minute%22%0A%09%09%09%09%09if dataAge %3E 1:%0A%09%09%09%09%09%09dataAgeDisplay += u%22s%22%0A%09%09%09%09%09dataAgeDisplay += u%22 old%22%0A%09%09%09%09%09dataAgeDisplay = dataAgeDisplay.format(dataAge=dataAge)%0A%0A%09%09%09%09#Not all replies include a placename%0A%09%09%09%09if 'name' in data and len(data%5B'name'%5D) %3E 0:%0A%09
 %09%09%09%09repl
@@ -2400,24 +2400,25 @@
 %09%09replytext 
++
 = u%22%7Bcity%7D (
@@ -2429,16 +2429,154 @@
 ntry%7D): 
+%22%0A%09%09%09%09elif 'country' in data%5B'sys'%5D and len(data%5B'sys'%5D%5B'country'%5D) %3E 0:%0A%09%09%09%09%09replytext += u%22Somewhere in %7Bcountry%7D: %22%0A%09%09%09%09replytext += u%22
 %7BtempC:.
@@ -2692,25 +2692,9 @@
 aAge
-:.0f%7D minutes old
+%7D
 )%22%0A%09
@@ -2827,28 +2827,16 @@
 renheit,
-%0A%09%09%09%09%09%09%09%09%09%09%09
  weather
@@ -2874,16 +2874,28 @@
 ption'%5D,
+%0A%09%09%09%09%09%09%09%09%09%09%09
  windSpe
@@ -2942,28 +2942,16 @@
 rection,
-%0A%09%09%09%09%09%09%09%09%09%09%09
  humidit
@@ -2989,24 +2989,31 @@
 aAge=dataAge
+Display
 )%0A%0A%09%09message

Fix some display issues