import time
import machine
import neopixel
import network
import urequests
# Configuration


NUM_PIXELS = 24  # Number of NeoPixels
PIN_NUM = 2     # Pin where NeoPixels are connected

# Initialize NeoPixel strip
np = neopixel.NeoPixel(machine.Pin(PIN_NUM), NUM_PIXELS)
rtc = machine.RTC()

target_hour = 22
target_minute = 34

def connectWifi():
  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!")

def refreshTime():
    data = urequests.get("http://worldtimeapi.org/api/timezone/Europe/Ljubljana").json()
    datetime_str = data['datetime']
    print(datetime_str)
    year = int(datetime_str[0:4])
    month = int(datetime_str[5:7])
    day = int(datetime_str[8:10])
    hour = int(datetime_str[11:13])
    minute = int(datetime_str[14:16])
    second = int(datetime_str[17:19])
    microsecond = int(datetime_str[20:26])

    rtc.datetime((year, month, day, data['day_of_week'], hour, minute, second,microsecond))

    # Verify the date and time have been set
    print(rtc.datetime())

def set_color(np, color, brightness):
    r, g, b = color
    r = int(r * brightness / 255)
    g = int(g * brightness / 255)
    b = int(b * brightness / 255)
    for i in range(np.n):
        np[i] = (r, g, b)
    np.write()

# Function to simulate sunrise
def sunrise_simulation(np, steps=100, delay=0.1):
    for i in range(steps):
        # Calculate the red, green, and blue values
        red = min(255, int(i * 255 / steps))
        green = min(100, int(i * 100 / steps))  # Limit green for a more realistic color
        blue = min(50, int(i * 50 / steps))    # Blue should be minimal
        
        color = (red, green, blue)
        
        # Calculate brightness incrementally from 1 to 255
        brightness = int(i * 255 / steps)
        
        # Set the color to the NeoPixel strip with brightness adjustment
        set_color(np, color, brightness)
        
        # Delay to create the animation effect
        time.sleep(delay)



def clear_pixels():
    for i in range(NUM_PIXELS):
        np[i] = (0, 0, 0)
    np.write()

def setPixels(data, delay, op = 2):
    clear_pixels()
    minTemp = max(min(data),1)
    maxTemp = max(data)
      # Define temperature thresholds (in Celsius)
    cold_threshold = 15  # Below this, it's cold (blue)
    cool_threshold = 20  # Below this, it's cool (blue-green)
    warm_threshold = 25  # Below this, it's warm (green-yellow)
    hot_threshold = 30   # Above this, it's hot (red)

           
    # RED GREEN BLUE
    for i,d in enumerate(data):
      normal = (d - minTemp) / (maxTemp - minTemp)
      red = int(255 * normal)
      blue = int(255 * (1 - normal))
      
      if op == 1:

        temp = d
        if temp < cold_threshold:
        # Cold - Blue
            np[i] = (0, 0, 255)
        elif temp < cool_threshold:
            # Cool - Blue to Green
            ratio = (temp - cold_threshold) / (cool_threshold - cold_threshold)
            np[i] = (0, int(255 * ratio), int(255 * (1 - ratio)))
        elif temp < warm_threshold:
            # Warm - Green to Yellow
            ratio = (temp - cool_threshold) / (warm_threshold - cool_threshold)
            np[i] = (int(255 * ratio), 255, 0)
        elif temp < hot_threshold:
            # Hot - Yellow to Red
            ratio = (temp - warm_threshold) / (hot_threshold - warm_threshold)
            np[i] = (255, int(255 * (1 - ratio)), 0)
        else:
            # Very Hot - Red
            np[i] = (255, 0, 0)
      if op == 2:
        np[i] = (0, red, blue)

      np.write()
      time.sleep_ms(delay)

def setPixelsUV(data, delay):
     for i,uv in enumerate(data):
        if uv <= 2:
            color = (0, 255, 0)  # Green
        elif uv <= 5:
            color = (255, 255, 0)  # Yellow
        elif uv <= 7:
            color = (255, 165, 0)  # Orange
        elif uv <= 10:
            color = (255, 0, 0)  # Red
        else:
            color = (128, 0, 128)  # Purple
        np[i] = color
        np.write()
        time.sleep_ms(delay)


def setPixelsDay(data,delay):
     for i,d in enumerate(data):
        if d == 0:
            color = (0, 0, 0)  # night
        else:
            color = (242, 219, 149)  #  day
        np[i] = color
        np.write()
        time.sleep_ms(delay)

def sunRise(toMax=10):
 
    
    print(brightness)
    # orange
    color = (255, 100, 50)


    def set_color(np, color, brightness):
        while wakeup:

            
            current_time = rtc.datetime()
            current_hour = current_time[4]
            current_minute = current_time[5]
            current_sec = current_time[6]
            #print(current_hour, current_minute,current_sec )

            rtcSec = current_hour*3600 + current_minute*60 + current_sec
            alarmTimeSec = target_hour*3600 + target_minute*60

            secDiff = rtcSec - alarmTimeSec 
            brightness = 255 * (secDiff//toMax*60)
            r, g, b = color
            r = int(r * brightness / 255)
            g = int(g * brightness / 255)
            b = int(b * brightness / 255)
            for i in range(np.n):
                np[i] = (r, g, b)
            np.write()

    # Adjust color with brightness
    set_color(np, color, brightness)


def rainMax(*l):
  
    return [max(z[0]) for z in zip(l)]
 

print(rainMax([1,0,0], [0,2,0],[0,0,3]))

connectWifi()
#refreshTime()




# API CALL
url = "https://api.open-meteo.com/v1/forecast?latitude=46.0511&longitude=14.5051&hourly=temperature_2m,rain,uv_index,is_day&daily=sunrise,sunset&timezone=Europe%2FBerlin&forecast_days=1"
#url = "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=rain&models=best_match,cma_grapes_global,bom_access_global,gfs_seamless,jma_seamless,icon_seamless,gem_seamless,meteofrance_seamless,arpae_cosmo_seamless,metno_seamless,knmi_seamless"
data = urequests.get(url).json()



temperature_2m = data["hourly"]["temperature_2m"]

#rain = rainMax(rain_best_match, rain_cma_grapes_global, rain_bom_access_global, rain_gfs_seamless, rain_jma_seamless, 
 #rain_icon_seamless, rain_gem_seamless, rain_meteofrance_seamless, rain_arpae_cosmo_seamless, rain_metno_seamles, 
 #rain_knmi_seamless  )
rain  = data["hourly"]["rain"]




uv = data["hourly"]["uv_index"]
isDay = data["hourly"]["is_day"]

#setPixels(temperature_2m, 100, 1)
#setPixels(rain, 100, 2)
#setPixelsUV(uv, 50)
#setPixelsDay(isDay, 50)


picked = 0
allPoss = 4
#sunRise()
while True:
    #sunrise_simulation(np)

    #current_time = rtc.datetime()
    current_hour = 22 #current_time[4]
    current_minute = 37 #current_time[5]
    current_sec = 0 #current_time[6]
    #print(current_hour, current_minute,current_sec )

    rtcSec = current_hour*3600 + current_minute*60 + current_sec
    alarmTimeSec = target_hour*3600 + target_minute*60

    secDiff = rtcSec - alarmTimeSec 
    print(secDiff)
    #if rtcSec - alarmTimeSec > 0:
    #  sunRise(secDiff)


 
    if picked == 0:
        print("TEMPERATURA")
        setPixels(temperature_2m, 50, 1)
        
    if picked == 1:
        print("DEŽ")
        setPixels(rain, 50, 2)
        
    if picked == 2:
        print("UV")
        setPixelsUV(uv, 50)
        
    if picked == 3:
        print("UV")
        setPixelsDay(isDay, 50)
      
    time.sleep_ms(2000)
    picked +=1
    picked %= allPoss