#!/bin/tclsh
#Version 1.1
#param 0 = Breitengrad (nördlich)
#param 1 = Längengrad (östlich)
#param 2 = künstlicher Horizont
#param 3 = PLZ

source /www/addons/lcd_msg/daemonize.tcl

load tclrega.so
puts "args: $argv"

set latitude [lindex $argv 0]
set longitude [lindex $argv 1]
set indoor_horizon [lindex $argv 2]
set plz [lindex $argv 3]
set timezone_start [expr {([clock scan "0 UTC"] - [clock scan "0"]) / 3600.0}]
puts "timezone: $timezone_start"

proc calcTwilightTimes {latitude longitude timezone horizon sunrisevar sunsetvar} {
  upvar $sunrisevar sunrise
  upvar $sunsetvar sunset
 
  set dayofyear [string trimleft [clock format [clock seconds] -format "%j"] "0"]
  set timediff [expr {-0.171*sin(0.0337 * $dayofyear + 0.465) - 0.1299*sin(0.01787 * $dayofyear - 0.168)}]
  set declination [expr {0.4095 * sin(0.016906 * ($dayofyear - 80.086) ) }]
  set suntime [expr {12*acos((sin($horizon/57.29578) - sin($latitude/57.29578)*sin($declination)) / (cos($latitude/57.29578)*cos($declination)))/3.141592}]
  set sunrise [expr {[clock scan "0"] + round((12 - $timediff - $suntime - $longitude/15.0 + $timezone)*3600)}]
  set sunset  [expr {[clock scan "0"] + round((12 - $timediff + $suntime - $longitude/15.0 + $timezone)*3600)}]
}

proc getTwilightHorizon {plz base_horizon} {
  set url http://www.google.com/ig/api?weather=$plz-Germany&hl=de
  catch {
    exec /usr/bin/wget -q -O /tmp/twilightweather.xml $url
    set f [open "/tmp/twilightweather.xml"]
    set a [read $f]
    close $f
    regexp "<current_conditions>(.*)</current_conditions>" $a dummy current
    foreach tag [split $current >] {
      regexp {<([^=>]*) data="([^=>"]*)"/} $tag dummy key value
        #" for editor
      set aCurrent($key) "$value"
    }
    puts "[clock format [clock seconds] -format "%H:%M:%S"]: current condition is \"$aCurrent(condition)\""
    file delete /tmp/twilightweather.xml
    switch $aCurrent(condition){
      "Klar"              {return [expr {$base_horizon + 0.2}]}
      "Meist sonnig"      {return [expr {$base_horizon + 1.5}]}
      "Teils sonnig"      {return [expr {$base_horizon + 3.0}]}
    }
  }
  return [expr {$base_horizon + 5.0}]
}

proc showTwilightTime x {
  clock format $x -format "%H:%M:%S"
}

proc displayValues {current_state srw_set ssw_set twilight_times} {
  set twilight_types "Astronom.: Nautisch: Bürgerlich: Standard: Indoor: Wetterabh.:"
  set display "siehe folgende Tabelle</div><br/>\n<table border=\"1\" bordercolor=\"#000000\" style=\"background-color:#5d6373\" width=\"100%\">"
  append display "<tr><td><b>Dämmerung</b></td><td><b>Morgens</b></td><td><b>Abends</b></td></tr>"
  for {set i 0} {$i < 6} {incr i} {
    
    if {$i == $current_state-1 || $i == 11-$current_state} then {
      append display "<tr><td><b>[lindex $twilight_types $i]</b></td><td>"
    } else {
      append display "<tr><td>[lindex $twilight_types $i]</td><td>"
    }      
    if {$i == $current_state-1} then {append display "<b>"}
    if {$i == 5 && !$srw_set} then {append display "<i>"}
    append display "[showTwilightTime [lindex $twilight_times $i]]"
    if {$i == 5 && !$srw_set} then {append display "</i>"}
    if {$i == $current_state-1} then {append display "</b>"}
    append display "</td><td>"
    if {$i == 12-$current_state} then {append display "<b>"}
    if {$i == 5 && !$ssw_set} then {append display "<i>"}
    append display "[showTwilightTime [lindex $twilight_times [expr {11-$i}]]]"
    if {$i == 5 && !$ssw_set} then {append display "</i>"}
    if {$i == 12-$current_state} then {append display "</b>"}
  }
  append display "</table>\n</td>"
  rega_script "dom.GetObject('Dämmerungszeiten').State('$display');"
}

calcTwilightTimes $latitude $longitude $timezone_start [expr {$indoor_horizon + 5.1}] sunrise_weather sunset_weather
calcTwilightTimes $latitude $longitude $timezone_start $indoor_horizon sunrise_indoor sunset_indoor
calcTwilightTimes $latitude $longitude $timezone_start -0.83333333 sunrise sunset
calcTwilightTimes $latitude $longitude $timezone_start -6 sunrise_civil sunset_civil
calcTwilightTimes $latitude $longitude $timezone_start -12 sunrise_nautical sunset_nautical
calcTwilightTimes $latitude $longitude $timezone_start -18 sunrise_astronomical sunset_astronomical

set twilight_times "$sunrise_astronomical $sunrise_nautical $sunrise_civil $sunrise $sunrise_indoor $sunrise_weather $sunset_weather $sunset_indoor $sunset $sunset_civil $sunset_nautical $sunset_astronomical"
set srw_set 0
set ssw_set 0
displayValues 0 $srw_set $ssw_set $twilight_times

for {set i 0} {$i < 12} {incr i} {
  set next_time [lindex $twilight_times $i]
  set now [expr {round([clock seconds] + [clock scan "0 UTC"] - [clock scan "0"] - $timezone_start*3600)}]
  puts "$now [clock seconds]"
  if {$i == 5} then {
    #sunrise weather
    puts "[clock format [clock seconds] -format "%H:%M:%S"]: retrieving weather condition for sunrise"
    calcTwilightTimes $latitude $longitude $timezone_start [getTwilightHorizon $plz $indoor_horizon] sunrise_weather dummy
    set next_time $sunrise_weather
    set srw_set 1
    set twilight_times [lreplace $twilight_times 5 5 $sunrise_weather]
    displayValues $i $srw_set $ssw_set $twilight_times
    puts "[clock format [clock seconds] -format "%H:%M:%S"]: weather sunrise at [clock format $next_time -format "%H:%M:%S"]"
  }
  if {$now < $next_time} then {
    puts "[clock format [clock seconds] -format "%H:%M:%S"]: current twilight state $i, sunlight state [expr {6-abs($i-6)}], next at [clock format $next_time -format "%H:%M:%S"]"
    rega_script "dom.GetObject('Dämmerung').State('$i');"
    rega_script "dom.GetObject('Tageslicht').State('[expr {6-abs($i-6)}]');"
    displayValues $i $srw_set $ssw_set $twilight_times
    puts $next_time
    puts $now
    after [expr {round(1000*($next_time - $now))}]
    if {$i == 6} then {
      #sunset weather
      puts "[clock format [clock seconds] -format "%H:%M:%S"]: retrieving weather condition for sunset"
      calcTwilightTimes $latitude $longitude $timezone_start [getTwilightHorizon $plz $indoor_horizon] dummy sunset_weather
      set next_time $sunset_weather
      set ssw_set 1
      set twilight_times [lreplace $twilight_times 6 6 $sunset_weather]
      displayValues $i $srw_set $ssw_set $twilight_times
      puts "[clock format [clock seconds] -format "%H:%M:%S"]: weather sunset at [clock format $next_time -format "%H:%M:%S"]"
      after [expr {round(1000*($next_time - $now))}]
    }
  }
}
rega_script "dom.GetObject('Dämmerung').State('12');"
rega_script "dom.GetObject('Tageslicht').State('0');"
displayValues 12 $srw_set $ssw_set $twilight_times
    
if {[file exists /tmp/twilight.pid]} then {
  catch {
    set f [open /tmp/twilight.pid]
    set filepid [read $f]
    close $f
    if {[pid] == $filepid} then {file delete /tmp/twilight.pid}
  }
}
