from tidal import *
import wifi
import datetime
from app import TextApp

class WetterApp(TextApp):
 BG = BLACK
 FG = WHITE
 def on_activate(self):
  super().on_activate()   
  self.window.println("WETTER FORECAST")
  self.window.println("===============") 
  if not wifi.status():
   self.window.println("Connecting to wifi")
   wifi.connect()
   wifi.wait()
   if not wifi.status():
    print("Connection failed!")
    return
   self.window.println(f"Connected to {wifi.get_ssid()}")
  self.window.println("Contacting MET Office")
  weather = get_weather()
  print_weather(self.window, weather)

# Set the entrypoint for the app launcher
main = WetterApp

import urequests
# Probably fine for EMFCamp 2022 but will shut down afterwards
# You can get your own key and secret in this URL: https://metoffice.apiconnect.ibmcloud.com/metoffice/production/
# under the section "Site Specific forecast"
METOFFICE_KEY="3880e8faf8955ed5be61e636478ba3a5"
METOFFICE_SECRET="e081a3e3ea3a0836ef3cbae07a3f714f"
ENDPOINT="https://rgw.5878-e94b1c46.eu-gb.apiconnect.appdomain.cloud/metoffice/production/v0/forecasts/point/hourly"

# As indicated by the EMF pin in Google Maps
LATITUDE="52.0393567"
LONGITUDE="-2.3795471"

def get_weather():
 url = f"{ENDPOINT}?includeLocationName=true&latitude={LATITUDE}&longitude={LONGITUDE}"
 headers = { "X-IBM-Client-Id": METOFFICE_KEY, "X-IBM-Client-Secret" : METOFFICE_SECRET }
 response = urequests.get(url, headers= headers)
 #print(type(response))
 results = response.json()
 response.close()
 return results
 
print("Hi8")
def print_weather(window, w):
 window.println("Location:")
 window.println(w['features'][0]['properties']['location']['name'])
 for i in [0,1,2]:
  timeSeries = w['features'][0]['properties']['timeSeries'][i]
  timeStr = currentdt.time().strftime('%H:%m')
  currentdt = datetime.datetime.fromisoformat(timeSeries['time'][:-1]) # Removing pesky Z at the end
  winddir = get_wind_direction(timeSeries['windDirectionFrom10m'])
  window.println(f"* {timeStr}")
  window.println(f" - Temp: {timeSeries['screenTemperature']}°C")
  window.println(f" - Rain: {timeSeries['probOfPrecipitation']}%")
  window.println(f" - Wind: {timeSeries['windSpeed10m']}m/s ({winddir})")

def get_wind_direction(d):
 if d > 0 and d <= 22.5 or d > 360-22.5:
  return "N"
 elif d > 22.5 and d <= 90-22.5:
  return "NE"
 elif d > 90-22.5 and d <= 90+22.5:
  return "E"
 elif d > 90+22.5 and d <= 180-22.5:
  return "SE"
 elif d > 180-22.5 and d <= 180+22.5:
  return "S"
 elif d > 180+22.5 and d <= 270-22.5:
  return "SW"
 elif d > 270-22.5 and d <= 270+22.5:
  return "W"
 else:
  return "NW"