#!/usr/bin/ruby
#
# Author: Norbert Wigbels - foobla.wigbels.de/uber-foobla
#
# HotHotWrite receives data from HotHotRead and writes it to the dbms
# Example of calling URL - http://www.wigbels.net/cgi-bin/hhw.rb?sensorid=1&data=23.4 &measuredat=2007-20-14


#------------------------------------------
# Tainted mode 0-4
$SAFE=1

#------------------------------------------
require 'mysql'
require 'cgi'
require 'logger'
require 'time'

# Standard header
print "Content-type: text/plain\n\n"

# Date 14 07 2009
day   = Time.now.strftime("%d")
month = Time.now.strftime("%m")
year  = Time.now.strftime("%Y")

# CGI - GET-Parameter
cgi	   = CGI.new

if cgi.has_key?('sensorid')
  sensorid = Integer(cgi['sensorid'])
end
if cgi.has_key?('data')
  data = Float(cgi['data'])
end
if cgi.has_key?('logyear')
  logyear = Integer(cgi['logyear'])
  yearbefore = logyear - 1
end


# Logger
log = Logger.new(STDOUT)
log.level = Logger::INFO


begin
  dbh = Mysql.real_connect("localhost", "hhw", "", "kraftwerk")

  # data provided?, insert - no data select->display
  if sensorid and data
    dbh.query( %Q"insert into sensor (sensorid, data, measuredat) values (#{sensorid.to_s}, #{data.to_s}, now())" )
    log.info("Inserted sensor: #{sensorid} with data: #{data}")
  else
    years = dbh.query( %Q"select count(distinct year(measuredat)) FROM sensor" ).fetch_row[0]
    # Auswertung Gesamtes Jahr, Monat, Vergleich Vorjahr
    myquery = %Q{ select sum(data), 'Liter Verbrauch in #{month}-#{logyear}' \
                  from sensor \
                  where year(measuredat) = '#{logyear}' and month(measuredat) = '#{month}'
                  union
                  select sum(data), 'Liter Verbrauch in #{month}-#{yearbefore}\n' \
                  from sensor \
                  where year(measuredat) = '#{yearbefore}' and month(measuredat) = '#{month}'
                  union \
                  select sum(data), 'Liter Gesamtverbrauch in #{logyear}' \
                  from sensor \
                  where year(measuredat) = '#{logyear}'
                  union
                  select sum(data), 'Liter Gesamtverbrauch in #{yearbefore}\n' \
                  from sensor \
                  where year(measuredat) = '#{yearbefore}'
                  union
                  select truncate(avg(data)/#{years},2), 'Durchschnittsverbrauch Gesamtjahr Liter/Tag' \
                  from \
                    (select sum(data) as data from sensor \
                     group by month(measuredat), day(measuredat)) \
                  as foo
                  union
                  select truncate(avg(data)/#{years},2), 'Durchschnittsverbrauch Sommmer Liter/Tag' \
                  from \
                    (select sum(data) as data from sensor \
                     where month(measuredat) in (4,5,6,7,8,9) \
                     group by month(measuredat), day(measuredat)) \
                  as foo
                  union
                  select truncate(avg(data)/#{years},2), 'Durchschnittsverbrauch Winter Liter/Tag' \
                  from \
                    (select sum(data) as data from sensor \
                     where month(measuredat) in (1,2,3,10,11,12) \
                     group by month(measuredat), day(measuredat)) \
                  as foo }                  
    res = dbh.query( myquery )
    while row = res.fetch_row do
       printf "%s\t%s\n", row[0], row[1]
    end
    puts "\n\n"
    # Auswertung Monat.
    res = dbh.query( %Q{ select month(measuredat), '#{logyear}', sum(data) \
                         from sensor \
                         where year(measuredat) = '#{logyear}'\
                         group by month(measuredat)
                         order by month(measuredat) desc } )
    puts "Datum\t\tVerbrauch (Liter)"
    puts "======================================================================================================================================================="
    while row = res.fetch_row do
      chart = (row[2].to_i / 1200)
      printf "%s-%s\t\t%s\t", row[0], row[1], row[2]
      chart.times {print "#"}
      print "\n"
    end
    puts "\n\n"
    # Auswertung Jahr: Kummuliert nach Tagen, Monat.
    res = dbh.query( %Q{ select day(measuredat), month(measuredat), '#{logyear}', sum(data) \
                         from sensor \
                         where year(measuredat) = '#{logyear}'\
                         group by month(measuredat), day(measuredat) \
                         order by month(measuredat) desc, day(measuredat) desc } )
    puts "Datum\t\tVerbrauch (Liter)"
    puts "======================================================================================================================================================="
    while row = res.fetch_row do
      chart = (row[3].to_i / 70)
      printf "%s-%s-%s\t%s\t", row[0], row[1], row[2], row[3]
      chart.times {print "#"}
      print "\n"
    end
    res.free
  end

rescue Mysql::Error => e
  log.fatal("Error code: #{e.errno}")
  log.fatal("Error message: #{e.error}")
  if e.respond_to?("sqlstate")
    log.fatal("Error SQLSTATE: #{e.sqlstate}")
  end
ensure
  # disconnect from server
  dbh.close if dbh
end
