# -*- coding: utf-8 -*-
import requests
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString

from . import Plugin


class Weather(Plugin):
    URL = 'https://query.yahooapis.com/v1/public/yql?format=json&q=' \
          'select * from weather.forecast where u="c" and woeid in ' \
          '(select woeid from geo.places(1) where text="{}")'

    @command
    def weather(self, mask: IrcString, target: IrcString, args: Dict):
        """Gets the weather from Yahoo weather API

        %%weather <location>...
        """
        req = requests.get(self.URL.format(' '.join(args['<location>'])))
        data = req.json()

        if 'error' in data:
            return '\x02[Weather]\x02 Error'
        elif not data['query']['results']:
            return '\x02[Weather]\x02 Location not found'
        else:
            res = data['query']['results']['channel']
            return '\x02[Weather]\x02 {city}, {region}, {country}: ' \
                   '\x02{temp}°{unit_temp} {text}\x02, ' \
                   '\x02{direction} {speed} {unit_speed}\x02' \
                .format(city=res['location']['city'],
                        region=res['location']['region'].strip(),
                        country=res['location']['country'],
                        temp=res['item']['condition']['temp'],
                        text=res['item']['condition']['text'],
                        direction='↑↗→↘↓↙←↖'[round(int(res['wind']['direction']) / 45) % 8],
                        speed=res['wind']['speed'],
                        unit_temp=res['units']['temperature'],
                        unit_speed=res['units']['speed'])