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


@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')


## Function to call Weather API ##
def getWeather(zip_code):
    ## Get request ##
    resp = requests.get("http://api.openweathermap.org/data/2.5/forecast?zip=" + str(zip_code) + ",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()

    forecasts = response['list']

    city = response['city']
    location = city['name']

    output = ""
    #for forecast in forecasts:
    # range() = start#, stop_before, #steps
    for forecast_id in range(0, 16):
        forecast = forecasts[forecast_id]

        ## Get data from forecast ##
        #location = forecast['name']
        #location = str(zip_code)

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

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

        cal_date = forecast['dt_txt']
        cal_date = int(cal_date[8:-9])

        curr_date = int(time.strftime("%d"))

        cal_day = ""
        if cal_date == curr_date:
            cal_day = "Today"
        elif cal_date == curr_date + 1 or cal_date == 1:
            cal_day = "Tomorrow"
#        elif cal_date == curr_date + 2 or cal_date == 1 or cal_date == 2:
#            cal_day = "The day after tomorrow"
        else:
            continue

        time_of_day = forecast['dt_txt']
        time_of_day = int(time_of_day[11:-6])
        
        time_ext = "AM"
        if time_of_day - 12 >= 0:
            time_of_day = time_of_day - 12
            time_ext = "PM"

        time_of_day = str(time_of_day) + time_ext

        if time_of_day == "0PM":
            time_of_day = "noon"

        if time_of_day == "0AM":
            time_of_day = "midnight"
            cal_day = "Tonight"

        # 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 = "("
        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)
        heat_index = round(heat_index)


        ## Add to the final string ##
        output = str(output + cal_day + " at " + str(time_of_day) + " it will be " + str(temp) + temp_units + " and " + weather_main + 
                 " with " + str(wind_speed) + wind_units + " wind and " + str(humidity) + humidity_units + " humidity" + 
                 ". " + wind_chill_text + heat_index_text + "\n")

    return output
