require "scripts/lua/functions"

----------------------------------------------------------------------------------------------------------
-- Script parameters
----------------------------------------------------------------------------------------------------------
--      Setting the time variables:
--      %a  abbreviated weekday name (e.g., Wed)
--      %A  full weekday name (e.g., Wednesday)
--      %b  abbreviated month name (e.g., Sep)
--      %B  full month name (e.g., September)
--      %c  date and time (e.g., 09/16/98 23:48:10)
--      %d  day of the month (16) [01-31]
--      %H  hour, using a 24-hour clock (23) [00-23]
--      %I  hour, using a 12-hour clock (11) [01-12]
--      %M  minute (48) [00-59]
--      %m  month (09) [01-12]
--      %p  either "am" or "pm" (pm)
--      %S  second (10) [00-61]
--      %w  weekday (3) [0-6 = Sunday-Saturday]
--      %x  date (e.g., 09/16/98)
--      %X  time (e.g., 23:48:10)
--      %Y  full year (1998)
--      %y  two-digit year (98) [00-99]
--      %%  the character `%´

year    = tonumber(os.date("%Y"));
month   = tonumber(os.date("%m"));
day     = tonumber(os.date("%d"));
hour    = tonumber(os.date("%H"));
min     = tonumber(os.date("%M"));
weekday = tonumber(os.date("%w"));

----------------------------------------------------------------------------------------------------------
-- Script functions
----------------------------------------------------------------------------------------------------------
function WhichSeason()
     local tNow = os.date("*t")
     local dayofyear = tNow.yday
     local season
     if (dayofyear >= 79) and (dayofyear < 172) then season = "Printemps"
     elseif (dayofyear >= 172) and (dayofyear < 266) then season = "ete"
     elseif (dayofyear >= 266) and (dayofyear < 355) then season = "Automne"
     else season = "Hiver"
     end
     return season
end

function IsWeekend()
     local dayNow = tonumber(os.date("%w"))
     local weekend
     if (dayNow == 0) or (dayNow == 6) then weekend = "True"
     else weekend = "False"
     end
     return weekend
end


function IsDark()
    local dark
   -- local now = heureEnMinute(uservariables["Couche"]) - 30
    local now = 60 * hour + min - 15
    local now2 = 60 * hour + min + 15

    debug (" variable sunset="..tostring(uservariables["Couche"]).." heureEnMinute="..tostring(heureEnMinute(uservariables["Couche"])))

    local sunsetMin = heureEnMinute(uservariables["Couche"])
    local sunriseMin = heureEnMinute(uservariables["Lever"])
    if (now > sunsetMin --timeofday['SunsetInMinutes'] or
        or now2 < sunriseMin --timeofday['SunriseInMinutes']
    ) then -- timeofday['Nighttime']) then
        dark = "True"
    else
        dark = "False"
    end

    debug("####### sunset "..tostring(timeofday['SunsetInMinutes'])..'  sunrise='
    ..tostring(timeofday['SunriseInMinutes'])..'  '..tostring(now)..' '..tostring(dark))

    return dark
end

----------------------------------------------------------------------------------------------------------
-- CommandArray
----------------------------------------------------------------------------------------------------------

commandArray = {}
if (min == 10 and hour == 0) then
  saison  = WhichSeason();
  weekend = IsWeekend();
  if (uservariables["Saison"] ~= season) then commandArray['Variable:Saison'] = tostring(saison)   end
  if (uservariables["Weekend"] ~= weekend) then commandArray['Variable:Weekend'] = tostring(weekend)   end

  debug(' Saison: ' .. saison .. ' ');
  debug(' Weekend: ' .. weekend .. ' ');
end

if (min % 1 == 0 and (hour >= 17 or hour < 10)) then
  dark    = IsDark();
  if (uservariables["Dark"] ~= dark) then
    --commandArray['Variable:Dark'] = tostring(dark)
    updateVar("Dark", dark)

  end
  debug(' Dark: ' .. dark .. ' ');
end


function checkLastUpdate(deviceIDX)
    local lastUpdateTime = lastUpdateOfDevice(deviceIDX)
    local currentTime    = os.time()
    local timeDifference = currentTime - lastUpdateTime

    -- Si la dernière mise à jour remonte à plus de 5 minutes
    if timeDifference > 300 then
        print("Le dispositif n'a pas été mis à jour depuis plus de 5 minutes.")
        -- Ajoutez ici le code pour effectuer une action en réponse à l'absence de mise à jour
    else
        print("Le dispositif a été mis à jour récemment.")
    end
end

if (min % 1 == 0 ) then
   checkLastUpdate(1182)
end

--if otherdevices['Debug'] == 'On' then
--    debug(' Year: '  .. year .. ' ');
--    debug(' Month: '  .. month .. ' ');
--    debug(' Day: '  .. day .. ' ');
--    debug(' Hour: '  .. hour .. ' ');
--    debug(' Minute: '  .. min .. ' ');
--    debug(' Weekday: '  .. weekday .. ' ');
--end

debug("Updating variables if necessary")

commandArray['Variable:Heure'] = tostring(hour)..":"..tostring(min)

return commandArray
