#!/usr/bin/env ruby

require 'socket'
require 'webrick'
require 'json'

TIMEOUT = 60
last_purge = Time.now.to_i
data = {}

Thread.new do
  server = WEBrick::HTTPServer.new :Port => 8080
  server.mount_proc "/data.json" do |req, res|
    res.status = 200
    res['Content-Type'] = 'application/json'
    res.body = data.values.to_json
  end
  server.start
end

sock = TCPSocket.new "radiobert.serv.zentralwerk.org", 30003
while line = sock.gets
  begin
    fields = line.chomp.split(/,/)
    msg_type = fields[1]
    hex = fields[4].downcase
    values = {
      :hex => hex,
      :last => Time.now.to_i
    }

    case msg_type
    when "1"
      values[:flight] = fields[10]

    when "3"
      unless fields[14].empty? or fields[15].empty?
        values[:lat] = fields[14].to_f
        values[:lon] = fields[15].to_f
      end
      unless fields[11].empty?
        values[:altitude] = fields[11].to_i
      end

    when "4"
      unless fields[12].empty?
        values[:speed] = fields[12].to_i
      end
      unless fields[13].empty?
        values[:track] = fields[13].to_i
      end
    end

    old_value = data[hex]
    if old_value
      old_value.merge! values
    else
      data[hex] = values
    end

    now = Time.now.to_i
    if now >= last_purge + TIMEOUT / 10
      data.delete_if { |hex, values|
        now >= values[:last] + TIMEOUT
      }
      last_purge = now
    end

  rescue
    STDERR.puts $!
  end
end

