require "scripts/lua/functions"

commandArray = {}


-- School Holiday Status Request from Domogeek API
-- http://api.domogeek.fr/static/doc/index.html#api-Domogeek-GetSchoolHoliday
-- Prerequis: 3 switch On/Off: "Zone A", "Zone B", "Zone C"

--recupere les minutes
time=os.time()
minutes=tonumber(os.date('%M',time))
heures=tonumber(os.date('%H',time))

-- Path to curl
-- Windows: curl = 'C:\\bin\\curl.exe'
curl = "curl"

-- Devices (Switch On/Off on virtual hardware)
--switchA = "Zone A"
switchB = "Zone B"
--switchC = "Zone C"

-- Function to get result of HTTP request
function os.capture(cmd, raw)
  local f = assert(io.popen(cmd, 'r'))
  local s = assert(f:read('*a'))
  f:close()
  if raw then return s end
  s = string.gsub(s, '^%s+', '')
  s = string.gsub(s, '%s+$', '')
  s = string.gsub(s, '[\n\r]+', ' ')
  return s
end

-- Function to update a switch
function updateZoneSwitch(zone, switch)
  local cmd = curl .. " -y 2 http://domogeek.entropialux.com/schoolholiday/" .. zone .. "/now"
  local vac = os.capture(cmd, true)
  print("School Holiday Status: " .. cmd .. ": " .. tostring(vac))

  if (vac == "False") then
    --if (otherdevices[switch] == "On") then
      --commandArray[switch] = "Off";
    --end
  else
    if (vac ~= "") then 
      --commandArray[switch] = "On";
    end
  end
end



-- Trigger at 0:02 every day
if ((minutes == 5 and heures == 2)) then

  -- Zone A
  -- updateZoneSwitch("A", switchA)

  -- Zone B
  updateZoneSwitch("B", "Zone B")

  -- Zone C
  -- updateZoneSwitch("C", switchC)
end

return commandArray
