import network,time,machine,ssd1306,random
from joke_fetcher import JokeFetcher
from facts_fetcher import FactsFetcher
from blinker import Blinker

i2c=machine.I2C(0,scl=machine.Pin(22),sda=machine.Pin(21))
oled=ssd1306.SSD1306_I2C(128,64,i2c)
fetcher1,fetcher2,blinker=FactsFetcher(),JokeFetcher(),Blinker(2)

def connect_wifi(ssid,password):
    machine.freq(160000000);time.sleep(1)
    station=network.WLAN(network.STA_IF);station.active(True)
    attempts,max_attempts,connected=0,5,False
    while attempts<max_attempts:
        try:
            station.connect(ssid,password);print("Connecting to WiFi...")
            if station.isconnected():connected=True;print("Connected to WiFi");blinker.blink(2,0.1,0.15);break
            else:attempts+=1
        except OSError as e:print(f"Error: {e}");attempts+=1
    return connected

def edit_text(text):
    replacements={"…":"...","‘":"'","’":"'","`":"'",""":'"',""":'"',"  ":" ","  ":" ","é":"e"}
    for old,new in replacements.items():text=text.replace(old,new)
    return ' '.join(text.split())

def display_on_oled(t1,t2,clear=False):
    machine.freq(80000000);line_height,lines,loop_count=8,[t2],1
    if clear:oled.fill(0)
    for _ in range(loop_count):
        oled.fill(0);oled.text(t1,0,3,1);oled.text(t2,0,15,1);oled.show();time.sleep(1.35)
        for line in lines:
            for i in range(len(line)*8):oled.fill(0);oled.text(t1,0,3,1);oled.text(line,-i,15,1);oled.show();time.sleep(0.0035)
            time.sleep(0.15)

wifi_connected=connect_wifi("Wokwi-GUEST","")
fetchers=[(fetcher2.get_text,"Here a joke:"),(fetcher1.get_text,"Here a fact:")]

while True:
    machine.freq(160000000);time.sleep(0.5)
    choice,display_text=random.choice(fetchers)
    content=edit_text(choice())
    display_on_oled(display_text,f"{content}",clear=True)
    machine.freq(160000000);time.sleep(0.5)