import time
import network
import urequests
from ..classes.location import Location
from ..classes.weather import CurrentCondition, Weather
import json

API_KEY = '3545ce42d0ba436e8dc164532250410'
ACTUAL_WEATHER = 'https://api.weatherapi.com/v1/current.json?key={{key}}&q={{city}}&aqi=yes'


class Wlan:
	def __init__(self, ssid, password):
		self.ssid = ssid
		self.password = password

	def mock_weather_data(self):
		data = """
			{
					"location": {
							"name": "Grosshansdorf",
							"region": "Schleswig-Holstein",
							"country": "Germany",
							"lat": 53.6667,
							"lon": 10.2833,
							"tz_id": "Europe/Berlin",
							"localtime_epoch": 1760779328,
							"localtime": "2025-10-18 11:22"
					},
					"current": {
							"last_updated_epoch": 1760778900,
							"last_updated": "2025-10-18 11:15",
							"temp_c": 8.3,
							"temp_f": 46.9,
							"is_day": 1,
							"condition": {
									"text": "Sonnig",
									"icon": "//cdn.weatherapi.com/weather/64x64/day/113.png",
									"code": 1000
							},
							"wind_mph": 2.5,
							"wind_kph": 4.0,
							"wind_degree": 31,
							"wind_dir": "NNE",
							"pressure_mb": 1029.0,
							"pressure_in": 30.39,
							"precip_mm": 0.0,
							"precip_in": 0.0,
							"humidity": 76,
							"cloud": 0,
							"feelslike_c": 8.2,
							"feelslike_f": 46.8,
							"windchill_c": 10.0,
							"windchill_f": 50.0,
							"heatindex_c": 9.9,
							"heatindex_f": 49.8,
							"dewpoint_c": 2.2,
							"dewpoint_f": 35.9,
							"vis_km": 10.0,
							"vis_miles": 6.0,
							"uv": 0.9,
							"gust_mph": 2.8,
							"gust_kph": 4.6,
							"air_quality": {
									"co": 163.678,
									"no2": 7.278,
									"o3": 47.0,
									"so2": 1.178,
									"pm2_5": 5.778,
									"pm10": 7.178,
									"us-epa-index": 1,
									"gb-defra-index": 1
							}
					}
			}"""

		filepath = 'restapi/mock-weather.json'
		try:
			with open(filepath, 'r', encoding='utf-8') as file:
				return json.load(file)
		except OSError:  # Use OSError instead of FileNotFoundError
			print(f"Error: File '{filepath}' not found.")
			return None
		except FileNotFoundError:
			print(f"Error: File '{filepath}' not found.")
			return None
		except json.JSONDecodeError as e:
			print(f"Error: Invalid JSON in '{filepath}': {e}")
			return None

	def connect(self):
		wlan = network.WLAN(network.STA_IF)
		wlan.active(True)
		wlan.connect(self.ssid, self.password)

		while not wlan.isconnected:
			print('connecting, please wait ...')
			time.sleep(1)

		print('connected! IP=', wlan.ifconfig()[0])

	def actual_weather(self, city='grosshansdorf', lang='de', test_mode=False) -> Weather:
		weather_url = (
			f'https://api.weatherapi.com/v1/current.json?key={API_KEY}&q={city}&aqi=yes&lang={lang}'
		)

		if not test_mode:
			self.connect()

			print(f'query: {weather_url}')
			r = urequests.get(weather_url)

			print('Status-Code:', r.status_code)
			json_resp = r.json()

			r.close()
		else:
			print('Status-Code: test_mode')
			# json_resp = WEATHER_QUERY_MOCK
			json_resp = self.mock_weather_data()

		loc = Location(**json_resp['location'])
		cc = CurrentCondition(**json_resp['current'])

		weather = Weather(location=loc, current=cc)

		return weather
