require "scripts/lua/functions"

commandArray = {}

local HEURE_DEB   = 9
local HEURE_FIN   = 17
local AZIMUTH_FIN = 270
local TEMP_MAX    = 25.5
local TEMP_MAX_2  = 29
local MIN_LUX     = 15000
local device_temp = 'BarometreLaGacilly'

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

local saison         = uservariables["Saison"]
local delaiFermeture = uservariables["DelaiFermetureVoletCoucheSoleil"]
local jourS          = josdGetJourSemaine()
local nuages         = tonumber(otherdevices['Nuage_LaGacilly']) 
local temp_ext       = getExternalTempRef(device_temp)

-- -------------------------------------------------------------------
-- Verification des volets ouverts si température trop basse
-- -------------------------------------------------------------------
if (minutes == 0 or minutes == 30 ) then

   print('Volets ########## Lancement du check fermeture velux du grenier ' ..heures..'h'..minutes)

   --tab = getValuesInTab('Exterieur_Cellier')
   -- val = otherdevices[device_temp]
   val, val2 = otherdevices_svalues[device_temp]:match("([^;]+);([^;]+)")


   local tmp = tonumber(val)

   print('Volets ########## Lancement du check fermeture velux du grenier ' ..heures..'h'..minutes..' tmp='..tostring(tmp))

   if (tmp < 14.0 and (otherdevices['Velux droit'] == 'Open' or otherdevices['Velux gauche'] == 'Open')) then
      commandArray['notification']="Volet ouvert#Un des volets du grenier est reste ouvert #0"
   end
end

-- -----------------------
-- Fermeture volet central
-- -----------------------
if minutes%5 == 0 and minutes < 2
  and (
  (heures >= 22 and (saison ~= "ete") and jourS ~= "mercredi" and (mois < 5 or mois >= 9)) -- or uservariables['Dark'] == "True")
  or (heures >= 23)
  )
then 
  print('Volets ------------------------------------------------------')
  print('Volets  Test fermeture volet Central '..otherdevices['VoletPorteSalon'])
  print('Volets ------------------------------------------------------')
  if (otherdevices['VoletPorteSalon'] ~= 'Closed') then 
    commandArray['VoletPorteSalon']='On'
  end
end

-- -----------------------
-- Ouverture volets
-- -----------------------
if minutes%10 == 3
  and heures < 10
  and (otherdevices['VoletCuisine'] == 'Closed' or otherdevices['VoletSalonTele'] == 'Closed')
  --and (saison == "Printemps" or saison == "ete")
then 
  print('Volets ------------------------------------------------------')
  print('Volets  Test ouverture volets jour chome='..tostring(josdJourChome())..' Absence='..otherdevices['AbsenceFamille']..' Vacances='..otherdevices['Vacances']
    ..' '..tostring(heures)..':'..tostring(minutes))
  print('Volets ------------------------------------------------------')
  
  local ouvertureVolet = false;
  if (josdJourChome() 
    or otherdevices['AbsenceFamille'] == 'On' 
    or otherdevices['Vacances']       == 'On'
  ) then
    print('Volets bloc 09:30 '..tostring(heures == 09 and minutes >= 30))
    if (heures == 09 and minutes >= 30) then 
        ouvertureVolet = true;
    end
  end
  if otherdevices['AbsenceFamille'] == 'Off' 
    and not josdJourChome() 
    and otherdevices['Vacances'] == 'Off'
    then
    print('Volets bloc 07:00 '..tostring(heures == 07 and minutes >= 00))
    if (heures == 07 and minutes >= 00) then 
        ouvertureVolet = true;
    end
  end

  print("Volets ouvertureVolet="..tostring(ouvertureVolet))
  if (ouvertureVolet == true) then
    print('Volets Ouverture volets jour chome='..tostring(josdJourChome())..' Absence='..otherdevices['AbsenceFamille']..' Vacances='..otherdevices['Vacances']
      ..tostring(heures)..' '..tostring(minutes))
    switchIfNeeded('VoletPorteSalon', 'Off')
    switchIfNeeded('VoletSalonTele', 'Off')
    switchIfNeeded('VoletCuisine', 'Off')
    --if (otherdevices['VoletVelux'] == 'Closed') then
    	switchIfNeeded('VoletVelux', 'Off')
    --end
  end  
end

-- -----------------------
-- Ouverture volets chambres
-- -----------------------
if minutes%5 == 0 and heures > 6 and heures < 13 
  --and (saison == "Printemps" or saison == "ete")
then 
  print('Volets ------------------------------------------------------')
  print('Volets          Test ouverture volets chambres')
  print('Volets ------------------------------------------------------')

  local presenceManon = (otherdevices['Manon'] == "On" or jourS == "samedi" or (jourS == "dimanche" and heures < 18) or otherdevices['Zone B'] == 'On')
  local presenceTheo  = (otherdevices['Theo'] == "On" or jourS == "samedi" or (jourS == "dimanche" and heures < 18) or otherdevices['Zone B'] == 'On')

  local val
  local val2
  val, val2 = otherdevices_svalues[device_temp]:match("([^;]+);([^;]+)")
  --val = otherdevices[device_temp]

  local temp = tonumber(val)
  -- ----------------
  -- Volet Somfy
  -- ----------------
  if (josdJourChome() or otherdevices['Vacances'] == 'On' 
    or (otherdevices['Conges'] == 'On' and otherdevices['AbsenceFamille'] == 'Off')) 
  then
    print('Volets          Test ouverture volets chambres bloc journee chomee')
    if (heures == 10 and minutes >= 30) then 
      switchIfNeeded('VoletChambreVirtuel', 'Off')
    end
    if (heures == 12 and minutes >= 30 and minutes <= 32) then 

        if (temp >= TEMP_MAX) then
          -- nothing
        else  
         switchIfNeeded('VoletManonVirtuel', 'Off')
         switchIfNeeded('VoletTheoVirtuel', 'Off')
        end 
    end
  else
    print('Volets          Test ouverture volets chambres bloc journee travaille')
    if (heures == 07 and minutes >= 45) then 
      switchIfNeeded('VoletChambreVirtuel', 'Off')
    end
    if (heures == 07 and minutes >= 45 and not presenceManon) then 
      switchIfNeeded('VoletManonVirtuel', 'Off')
    end
    if (heures == 07 and minutes >= 45 and not presenceTheo) then 
      switchIfNeeded('VoletTheoVirtuel', 'Off')
    end
    if (heures == 12 and minutes >= 30 and minutes <= 32) then 
      if (temp >= TEMP_MAX) then
        -- nothing
      else  
        if presenceManon then
          switchIfNeeded('VoletManonVirtuel', 'Off')
        end
        if presenceTheo then
          switchIfNeeded('VoletTheoVirtuel', 'Off')
        end

      end
    end 
  end
end

if minutes%1 == 0 and heures >= 19 and (saison == "ete")
  and uservariables['VoletsSomfy'] ~= 'open'
  and uservariables['Dark'] ~= "True"
then 

  local evolution = tonumber(uservariables['AugmentationTempExterieure'])

  local tempChambre = getTemperatureFromDevice('Chambre')

  print("tempChambre="..tostring(tempChambre).." temp_ext="..tostring(temp_ext).." evolution="..tostring(evolution))

  if (temp_ext + evolution <= tempChambre) then
      commandArray['Variable:VoletsSomfy'] = "open"

      print("SOMFY Volets test ouverture volets : temp en baisse")
      print("SOMFY Volets Lancement script somfy")

      os.execute("/opt/domoticz/scripts/voletsSomfy.sh u")
  end
end

-- ---------------------------------------------------------------------------------------
-- Fermeture des volets  
-- ---------------------------------------------------------------------------------------
--print("Volets DARK=="..tostring(uservariables['Dark'] == "True"))
if minutes%5 == 0  
 -- (saison ~= "Ete")
  and (
    otherdevices['VoletCuisine'] == 'Open' or otherdevices['VoletSalonTele'] == 'Open'
    --or otherdevices['VoletChambreVirtuel'] == 'Open' 
    --or otherdevices['VoletManonVirtuel'] == 'Open'
    --or otherdevices['VoletTheoVirtuel'] == 'Open' 
    )
  and (heures >= 18 or 
      (
        (heures >= 17 and minutes >= 30) and (
          uservariables['Dark'] == "True" 
          or (
             tonumber(otherdevices['Lux']) < tonumber(uservariables["LuxMini"])
            )
        )
      )
    )
then
  print('Volets ------------------------------------------------------')
  print('Volets          Test fermeture volet ')
  print('Volets ------------------------------------------------------')
    
   print('Volets ####### Comparaison heure vs Couche du soleil ========>'..uservariables["Heure"].."     couché "..uservariables["Couche"])
   --print('Volets ####### Lancement du check test ' ..heures..'h'..minutes..' volet cuisine '..otherdevices['Exterieur_Cellier']..' svalues='..otherdevices_svalues['Exterieur_Cellier']..' VoletCuisine='..otherdevices['VoletCuisine'])
   --tmp = otherdevices_svalues['Exterieur_Cellier']
   --tab = split(tmp, ";")

   -- val = otherdevices[device_temp]
   print("Volets ######### Check fermeture : temperature lue par "..device_temp.." "..temp_ext)

   temp = temp_ext --tonumber(val)

   if (
        (
          (
            (temp < 6.0 and whenDark() <= 0)  
            or (temp < 8 and whenDark() <= -10)
            or (temp < 10 and whenDark() <= -20)
          )
        )
        or (
          uservariables['Dark'] == "True"
        )
      )
    then
      local temp_chambre = getTemperatureFromDevice('Chambre')

      print(temp_chambre)

      print("Volets ######### Dans temperature exterieure la gacilly "..tostring(temp_ext)..' temp_chambre'..tostring(temp_chambre))
      if mois >= 6 and mois <= 9 and temp_ext < temp_chambre and temp_ext >= 21 and temp_chambre > 23 then   
          if (otherdevices['VoletCuisine'] == 'Open' and otherdevices['VoletSalonTele'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
            print("Volets Lancement volets2 On 17")
            os.execute("/opt/domoticz/scripts/volets2.sh On 17 &")
          end
      else
        print("Volets Lancement un par un")

        if (otherdevices['VoletCuisine'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20) ) then
           commandArray['VoletCuisine']='On'
        end
        if (otherdevices['VoletSalonTele'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
            commandArray['VoletSalonTele']='On'
        end
        if (otherdevices['VoletChambreVirtuel'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
            commandArray['VoletChambreVirtuel']='On'
        end
        if (otherdevices['VoletManonVirtuel'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
            commandArray['VoletManonVirtuel']='On'
        end
        if (otherdevices['VoletTheoVirtuel'] == 'Open') then -- or (minutes % 10 == 0 and heures <=20)) then
          commandArray['VoletTheoVirtuel']='On'
        end
      end
      switchIfNeeded('VoletVelux', 'On')
   else
      print("Volets ############ PAS DANS LE IF")
   end

end

-- ------------------------------------------------------------------------------
-- Ouverture des volets en fonction de la temperature exterieure Hiver et Automne
-- ------------------------------------------------------------------------------
if minutes%5 == 0 
  and heures <= HEURE_DEB 
  and ((heures >= 9 and josdJourChome()) or (heures > 6 and not josdJourChome()))
  and (saison == "Hiver"  or saison == "Automne")
  and (greater2(uservariables["Heure"],uservariables["Lever"], - 30)) -- heures >= 20
  and (otherdevices['VoletCuisine'] == 'Closed' 
    or otherdevices['VoletSalonTele'] == 'Closed' 
    or otherdevices['VoletPorteSalon'] == 'Closed'
    or otherdevices['VoletVelux'] == 'Closed'
    or otherdevices['VoletChambreVirtuel'] == 'Closed' 
    or otherdevices['VoletManonVirtuel'] == 'Closed'
    or otherdevices['VoletTheoVirtuel'] == 'Closed' 
    )
then
  print('Volets ------------------------------------------------------')
  print('Volets          Test ouverture volet ')
  print('Volets ------------------------------------------------------')

  print('Volets ####### Comparaison heure vs Lever du soleil ========>'..uservariables["Heure"]..
    "     "..uservariables["Lever"])
  print('Volets ####### Lancement du check test ' ..heures..'h'..minutes..' volet cuisine '
    ..otherdevices['Exterieur_Cellier']..' svalues='..otherdevices_svalues[device_temp]..' VoletCuisine='..otherdevices['VoletCuisine'])

  temp = temp_ext --
  if (temp > 12.0 
    or (heures >=9 and minutes >= 30 and josdJourChome())
    or (heures > 6 and not josdJourChome())
  ) then
    if (otherdevices['VoletCuisine'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
      commandArray ['VoletCuisine']='Off'
    end
    if (otherdevices['VoletSalonTele'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
      commandArray['VoletSalonTele']='Off'
    end
    if (otherdevices['VoletPorteSalon'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
      commandArray['VoletPorteSalon']='Off'
    end
    if (otherdevices['VoletVelux'] == 'Closed' or (minutes % 10 == 0 and heures == 9)) then
      commandArray['VoletVelux']='Off'
    end
--    if (otherdevices['VoletChambreVirtuel'] == 'Closed') then -- or (minutes % 10 == 0 and heures <=20)) then
--        commandArray['VoletChambreVirtuel']='Off'
--    end
--    if (otherdevices['VoletManonVirtuel'] == 'Closed') then -- or (minutes % 10 == 0 and heures <=20)) then
--        commandArray['VoletManonVirtuel']='Off'
--    end
--    if (otherdevices['VoletTheoVirtuel'] == 'Closed') then -- or (minutes % 10 == 0 and heures <=20)) then
--      commandArray['VoletTheoVirtuel']='Off'
--    end    
  end
end

-- ------------------------------------------------------------------------------
-- fermeture des volets en fonction de la temperature exterieure en ete
-- ------------------------------------------------------------------------------
if (minutes%5 == 0 --and uservariables['Dark'] == "False"
and (heures > HEURE_DEB and heures < HEURE_FIN))
--and (saison == "ete")
--and (greater(uservariables["Heure"] , uservariables["Lever"])) -- heures >= 20
--and (otherdevices['VoletCuisine'] == 'Open' or otherdevices['VoletSalonTele'] == 'Open' or otherdevices['VoletPorteSalon'] == 'Open')
then
  print('Volets ------------------------------------------------------')
  print('Volets          Test fermeture volet Ete')
  print('Volets ------------------------------------------------------')

  print('Volets ####### Lancement du check test ' ..heures..'h'..minutes..
    ' temp cellier '..otherdevices['Exterieur_Cellier']..
    ' svalues='..otherdevices_svalues[device_temp]..
    ' VoletCuisine='..otherdevices['VoletCuisine']..
    ' nuages='..tostring(nuages))
  
  local temp = temp_ext
  if (saison == "ete" or temp >= TEMP_MAX) then
    -- Lecture des lux pour ne pas fermer si ciel couvert
    -- local lux = tonumber(otherdevices['Lux'])

    print("Volets "..device_temp.." "..otherdevices_svalues[device_temp]
      .." volet cuisine "..otherdevices['VoletCuisine']..
      " volet tele "..otherdevices['VoletSalonTele']..
      " volet salon"..otherdevices['VoletPorteSalon'])

    if temp >= TEMP_MAX 
      and (otherdevices['VoletCuisine'] == 'Open' 
      and otherdevices['VoletSalonTele'] == 'Open'
      and otherdevices['VoletPorteSalon'] == 'Open') 
      --and tonumber(otherdevices['Sun Altitude']) > 50
      --sand (nuages < 50 or temp >= TEMP_MAX_2)
    then
        commandArray['Variable:VoletsSomfy'] = "close"

        print("Volets test fermeture volets : temp élevée lux"..tostring(lux))
      -- if lux > MIN_LUX then
        if temp >= TEMP_MAX_2 then
         print("Volets Lancement script 2 temp élevée volets2.sh on 15")

         os.execute("/opt/domoticz/scripts/volets2.sh On 15 &")
        else 
          print("Volets Lancement script 1 temp élevée volets.sh on ")

         os.execute("/opt/domoticz/scripts/volets.sh On &")
        end
      -- end
    end
  end
  if (temp >= TEMP_MAX_2 and heures == 13 and minutes == 00 
    and jours ~= 'samedi' and jours ~= "dimanche"
    ) then
      commandArray['Variable:VoletsSomfy'] = "close"

      print("Volets test fermeture volets : temp très élevée lux"..tostring(lux))
         print("Volets Lancement script somfy")

         os.execute("/opt/domoticz/scripts/voletsSomfy.sh d")
      -- end
  end
end


-- print("Volets Sun Altitude=" ..otherdevices['Sun Altitude'])

-- ------------------------------------------------------------------------------
-- Réouverture après la vague de chaleur ETE
-- ------------------------------------------------------------------------------
-- print("Volets Azimuth="..otherdevices["Sun Azimuth"])
if (minutes%5 == 0
  and ((heures > HEURE_FIN and whenDark() > 60)) --heures <= 19)) 
  and (saison == "ete" or (mois >= 5 and mois <= 10 ))
) then

  -- val = otherdevices[device_temp]

  print("Volets -- ------------------------------------------------------------------------------")
  print("Volets -- Réouverture après la vague de chaleur ETE")
  print("Volets -- ------------------------------------------------------------------------------")

  print("Volets "..device_temp.." "..otherdevices["Exterieur_Cellier"].." "..tostring(temp_ext)..
    otherdevices['VoletCuisine'].."  "..otherdevices['VoletSalonTele'].."  "..otherdevices['VoletPorteSalon'])

  local temp = temp_ext

  if ((temp <= 26 or (temp <= TEMP_MAX and heures >= 18) or (heures >= 19)
    or tonumber(otherdevices['Sun Altitude']) <= 30
    )
    --or tonumber(otherdevices["Sun Azimuth"]) > AZIMUTH_FIN)
    and (otherdevices['VoletCuisine'] == 'Closed' or 
         otherdevices['VoletSalonTele'] == 'Closed' or
         otherdevices['VoletPorteSalon'] == 'Closed'))
  then
    print("Volets Ouverture volets : temp en baisse")
    if temp <= TEMP_MAX then
      print("Volets Lancement volets2 Off 20")

      os.execute("/opt/domoticz/scripts/volets2.sh Off 20 &")
    else
      print("Volets Lancement volets3 Off 20")

      os.execute("/opt/domoticz/scripts/volets3.sh Off 20 &")

    end
  end

end
 
-- ------------------------------------------------------------------------------
-- Activation ventilation grenier
-- ------------------------------------------------------------------------------
if (minutes%5 == 0
) then
  local temp     = tonumber(otherdevices_svalues['Cheminee'])

  print("Volets "..device_temp.." Test ventilation "..otherdevices_svalues[device_temp].." externe="..temp_ext.." salon="..temp)

  local variation = variationTemp2('Cheminee', 30) -- variation des 10 dernières minutes
  print("Variation Chemine="..tostring(variation))

  if (temp_ext < 15 and (temp >= 20 or variation > 1) and heures >= 10) then
    print("Activation ventilation")
    commandArray['Ventilation'] = 'On'
  else
    print("Désactivation ventilation")
    commandArray['Ventilation'] = 'Off'
  end

end


return commandArray
