import time
import urequests as requests
import ujson
from machine import Pin, I2C
import ssd1306
import network

i2c = I2C(0, scl=Pin(22), sda=Pin(21))

oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

def fetch_metals_data():
    api_key = "d23a4d60b28c6911f4554dc8a02e6b98"
    url = f"https://api.metalpriceapi.com/v1/latest?api_key={api_key}&base=USD&currencies=EUR,XAU,XAG"

    try:
        response = requests.get(url)
        if response.status_code == 200:
            data = ujson.loads(response.text)

            # Extract metals data
            euro_to_usd = data["rates"]["EUR"]
            gold_price_per_gram = data["rates"]["XAU"]
            silver_price_per_gram = data["rates"]["XAG"]

            # Display data on OLED
            oled.fill(0)
            oled.text("USD: $" + str(euro_to_usd), 10, 10)
            oled.text("GLD: $" + str(gold_price_per_gram), 10, 25)
            oled.text("SLVR: $" + str(silver_price_per_gram), 10, 40)
            oled.show()

        else:
            print("Error: Unable to fetch data. Status code:", response.status_code)

    except Exception as e:
        print("Error fetching data:", e)

# WiFi connection
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
    print(".", end="")
    time.sleep(0.1)
print(" Connected!")

try:
    while True:
        fetch_metals_data()

except KeyboardInterrupt:
    oled.fill(0)
    oled.show()