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, math


@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):
    ## Get request ##
    resp = requests.get("http://api.openweathermap.org/data/2.5/weather?zip=47715,us&units=imperial&APPID=ecf63d9fa178fca8a4ab21b49e9bb456")

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

    response = resp.json()


    ## Get data from request ##
    location = response['name']

    weather = response['weather']
    weather = weather[0]
    weather_main = weather['main']
    weather_desc = weather['description'] 

    main = response['main']
    temp = main['temp']
    humidity = main['humidity']
    wind = response['wind']
    wind_speed = wind['speed']

    # Asked for Imperial units in API request
    temp_units = 'F'
    wind_units = 'mph'
    humidity_units = '%'


    ## Wind Chill ##
    # Wind speed as noted in: https://answers.yahoo.com/question/index?qid=20091020183148AAHm3kB&guccounter=1
    # More official source: https://www.weather.gov/media/epz/wxcalc/windChill.pdf
    wind_chill = 35.74 + (0.6215 * temp) - (35.75 * (wind_speed**0.16)) + (0.4275 * temp * wind_speed**0.16)


    ## Heat Index ##
    # Official formula: https://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml
    heat_index = -42.379 + 2.04901523*temp + 10.14333127*humidity - 0.22475541*temp*humidity - 0.00683783*temp*temp - 0.05481717*humidity*humidity + 0.00122874*temp*temp*humidity + 0.00085282*temp*humidity*humidity - 0.00000199*temp*temp*humidity*humidity

    if humidity < 13 and temp >= 80 and temp <= 112:
        heat_index -= ((13-humidity)/4)*math.sqrt((17-abs(temp-95.))/17)

    if humidity > 85 and temp >= 80 and temp <= 87:
        heat_index += ((humidity-85)/10) * ((87-temp)/5)

    if heat_index < 80:
        heat_index = 0.5 * (temp + 61.0 + ((temp-68.0)*1.2) + (humidity*0.094))
        heat_index = (heat_index + temp) / 2


    ## Check if wind chill or heat index is applicable ##
    # Rules found here under the map: https://www.mesonet.org/index.php/weather/map/wind_chill_heat_index1/air_temperature
    guess = "My guess is that's a "
    wind_chill_text = ""
    if temp < 50 and wind_speed > 5:
        wind_chill = round(wind_chill)
        wind_chill_text = guess + "wind chill of " + str(wind_chill) + temp_units + ". "
    else:
        wind_chill = temp

    heat_index_text = ""
    if temp > 80:
        heat_index = round(heat_index)
        heat_index_text = guess + "heat index of " + str(heat_index) + temp_units + ". "
    else:
        heat_index = temp


    ## Who doesn't want to go? ##
    besides_default = ' (Besides'
    besides = besides_default

    # Formula for temp/wind speed is to make sure that if it's too windy Chad doesn't go.
    # The denominator controls how powerful the wind speed is taken into account and gets bigger as it increases.
    chad_hates_wind = (temp/(wind_speed*(wind_speed*0.05)))
    if wind_chill <= 32 or heat_index >= 100 or chad_hates_wind < 3:
        if besides != besides_default:
            besides += ','
        besides += ' Chad'

    if (temp > 95 and humidity > 40):
        if besides != besides_default:
            besides += ','
        besides += ' Zach'

    if True:
        if besides != besides_default:
            besides += ','
        besides += ' Dan'

    if besides == besides_default:
        besides = ''
    else:
        besides += ')'

    comma_count = besides.count(',')
    if comma_count == 1:
        besides = besides.replace(',', ' and')
    elif comma_count >= 2:
        besides = besides.replace(',', '|', comma_count)
        besides = besides.replace('|', ',', comma_count-1)
        besides = besides.replace('|', ', and')


    ## Check if wind chill or heat index is applicable ##
    # Rules found here under the map: https://www.mesonet.org/index.php/weather/map/wind_chill_heat_index1/air_temperature
    guess = "My guess is that's a "
    wind_chill_text = ""
    if temp < 50 and wind_speed > 5:
        wind_chill = round(wind_chill)
        wind_chill_text = guess + "wind chill of " + str(wind_chill) + temp_units + ". "

    heat_index_text = ""
    if temp > 80:
        heat_index = round(heat_index)
        heat_index_text = guess + "heat index of " + str(heat_index) + temp_units + ". "


    ## Round numbers ##
    temp = round(temp)
    wind_speed = round(wind_speed)


    ## Build the final string ##
    output = str(location + " is " + str(temp) + temp_units + " and " + weather_main + 
             " with a wind speed of " + str(wind_speed) + wind_units + " and humidity of " + str(humidity) + humidity_units + 
             ". " + wind_chill_text + heat_index_text +
             "Who wants to walk?" + besides)

    return output
