#!/usr/bin/python3

# Python program to find current weather details of any city
# using openweathermap api

# import required modules for weather
import os
import requests, json
import urllib.request
import urllib.parse
from datetime import date,datetime
from datetime import time
import toml

# print diagnostic values if True else skip if False
diagnosticFlag = True
#diagnosticFlag = False


# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed

settingsFile = 'settings.toml'
try:
	with open(settingsFile, 'r') as f:
		config = toml.load(f)
except:
	print("File ", settingsFile," could not be opened.")
	print("This file must be in the same directory as the main program.")
	exit(-1)


###################### Replace these with your Open Weather KEY ##########################

# This is the OpenWeather API key. 
api_key = config['API_KEY']


##################### Replace these with your Adafruit Feed KEY ##########################

# These are no longer valid. Replace these values with your own username and key code.
ADAFRUIT_IO_USERNAME = config['ADAFRUIT_IO_USERNAME']
ADAFRUIT_IO_KEY = config['ADAFRUIT_IO_KEY']




##########################################################################################



# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"

# Give city name
location_name = "Zobo,Ma,Us"
locationList = location_name.split(",")
cityName,stateName,countryName = locationList


# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + location_name

# get method of requests module
# return response object
response = requests.get(complete_url)

# json method of response object
# convert json format data into
# python format data
x = response.json()

if x["cod"] != 200:
 print("Invalid return code")
 print("x = ",x)

# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":

    # Uncomment the next print line to show the weather in dictionary format
    #    print("x = ",x)

    coordinates = x["coord"]
    latitude = coordinates["lat"]
    longitude = coordinates["lon"]

    # Uncomment the next two lines to print the latitude and longitude
    #    print("coordinates = ",coordinates)
    #    print(latitude,longitude)

    # store the value of the "main" dictionary key in variable y
    y = x["main"]

    # store the value corresponding to the "temp" key of y
    current_temperature = y["temp"]

    # store the value corresponding to the "pressure" key of y
    current_pressure = y["pressure"]

    # store the value corresponding to the "humidity" key of y
    current_humidity = y["humidity"]

    # store the value of "weather" key in variable z
    z = x["weather"]

    # store the value corresponding to the "description" key at the 0th index of z
    weather_description = z[0]["description"]

    # print following values if True else skip if False
    if(diagnosticFlag):
        print(" Temperature (in kelvin unit) = " +
              str(current_temperature) +
              "\n atmospheric pressure (in hPa unit) = " +
              str(current_pressure) +
              "\n humidity (in percentage) = " +
              str(current_humidity) +
              "\n description = " +
              str(weather_description))
        print("\n")

    fahrenheit = 9/5*(current_temperature-273) + 32
    pressure = current_pressure * .0145037738
    today = date.today()
    current_time = time()
    now = datetime.now()
    t = now.strftime("%H:%M:%S")
    sampleDate = f"{today.year:4d}-{today.month:02d}{today.day:02d}"

    # print following values if True else skip if False
    if(diagnosticFlag):
        print(f"{today.year:4d}-{today.month:02d}{today.day:02d}   {t}")
        print()
        print(f"Predicted weather for  {location_name} at {t} on {today.year:4d}-{today.month:02d}{today.day:02d}")
        print(f"Temperature  =  {fahrenheit:.2f} F")
        print(f"Pressure     =  {pressure:.2f} psi")
        print(f"Humidity     =  {current_humidity:.0f}%")

        print(str(weather_description))

else:
    print(" City Not Found ")


weatherRecord = {
    "sampleDate": sampleDate,
    "sampleTime": t,
    "city": cityName,
    "state": stateName,
    "country": countryName,
    "latitude": latitude,
    "longitude": longitude,
    "temperature": f"{fahrenheit:.2f}",
    "temperatureUnits": "F",
    "pressure" : f"{pressure:.2f}",
    "pressureUnits": "psi",
    "humidity" : current_humidity,
    "description": weather_description
}

# print following values if True else skip if False
if(diagnosticFlag):
    print("\nweatherRecord")
    print(weatherRecord)

    jsonWeather = json.dumps(weatherRecord,indent=4 )
    print("\njsonWeather")
    print(jsonWeather)

##########################################################################################




# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

#### Send data to the predicted outside feeds.

if(diagnosticFlag):
   print("Sending Temperature")

temperature_feed = aio.feeds('outsidetemperature')
aio.send(temperature_feed.key, str(fahrenheit))

if(diagnosticFlag):
    print("Sending Humidity")

temperature_feed = aio.feeds('outsidehumidity')
aio.send(temperature_feed.key, str(current_humidity))

if(diagnosticFlag):
    print("Sending Pressure")

temperature_feed = aio.feeds('outsidepressure')
aio.send(temperature_feed.key, str(pressure))



