from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import requests, json


@csrf_exempt
def index(request):
    # Get Zip code from request
    print("Request=")
    print(request)
    print("Request body=")
    print(request.body)

    # Get weather string - ZIP is ignored for now
    print("Getting weather...")
    weather_string = getWeather(47715)
     
    print("Creating payload...")
    payload = { 'response_type': "in_channel", 'text': weather_string }
    print("payload=")
    print(payload)
    print("dumps(payload)=")
    print(json.dumps(payload))

    print("Returning payload...")
    return HttpResponse(json.dumps(payload), content_type='application/json')
    #return HttpResponse(data=weather_string, status=status.HTTP_200_OK)
    #return HttpResponse(status=status.HTTP_200_OK)
    #return Response(status=status.HTTP_200_OK)

    print("Done returning. ;)")


def getWeather(zip_code):
    return "Sorry, Yahoo APIs are no longer easily available and I don't know of any others yet. Try looking through Cheryl's office for the weather and let us know if it's worth risking a walk."
    resp = requests.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Evansville%2C%20in%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")

    if resp.status_code != 200:
        # This means something went wrong.
        raise ApiError('GET YahooWeather {}'.format(resp.status_code))

    weather = resp.json()

    query = weather['query']
    results = query['results']
    channel = results['channel']
    item = channel['item']
    condition = item['condition']

    location = item['title']
    temp = condition['temp']
    text = condition['text'].lower()

    units = channel['units']
    temp_units = units['temperature']
    wind_units = units['speed']

    wind = channel['wind']
    wind_speed = wind['speed']
    wind_chill = wind['chill']

    output = location + " are " + temp + temp_units + " and " + text + " with a wind speed of " + wind_speed + wind_units + ", resulting in a wind chill temperature of " + wind_chill + temp_units + ". Who wants to walk?"

    return output
