#!/usr/bin/perl -w

# Our database
$dbname = 'osm';

# Default verbosity level? Can be increased with -v, decreased with -q
$verblev = 0;

# The area which we cover
$x1 = 11.01;
$y1 = 49.56;
$x2 = 11.04;
$y2 = 49.58;

# There should be no need to touch anything below this line.
# ---------------------------------------------------------------------------

use DBI;
use POSIX qw(strftime mktime);
use Pg::hstore;

# Par. 0: Level on which this gets printed
# Par. 1: Text
sub printlev($$) {
  unless (defined($printlev_atbeginofline)) { $printlev_atbeginofline = 1; }
  if ($verblev >= $_[0]) {
    if ($printlev_atbeginofline) {
      print(strftime("[%Y%m%d-%H%M%S] ", localtime(time())));
    }
    print($_[1]);
    if ($_[1] =~ m/\n$/) {
      $printlev_atbeginofline = 1;
    } else {
      $printlev_atbeginofline = 0;
    }
  }
}

# Par. 0: default value to return if nothing is defined
# Par. 1: the hashref containing our variables.
# Par. 2: variables to query. The LAST one that exists will be returned.
sub fetchlastofhr($$@) {
  my $res; my $hr; my @vns;
  ($res, $hr, @vns) = @_;
  for (my $i = 0; $i < @vns; $i++) {
    my $vn = $vns[$i];
    if (defined($hr->{$vn})) {
      $res = $hr->{$vn};
    }
  }
  return $res;
}

# ----------------------------------------------------------------------------
# main()
# ----------------------------------------------------------------------------

# Parse commandline
foreach $a (@ARGV) {
  if ($a eq '-q') {
    $verblev--;
  } elsif ($a eq '-v') {
    $verblev++;
  } else {
    print("Unknown parameter: $a\n");
    print("Syntax: $0 [-q] [-v]\n");
    print(" -q decreases verbosity, -v increases verbosity.\n");
    exit(1);
  }
}

unless ($dbh = DBI->connect("dbi:Pg:dbname=$dbname","","")) {
  print(STDERR "Failed to open database. Please try again later.\n"); exit(1);
}

$tx1 = $dbh->selectrow_array("select ST_X(ST_transform(ST_GeomFromText('POINT($x1 $y1)', 4326), 900913))");
$ty1 = $dbh->selectrow_array("select ST_Y(ST_transform(ST_GeomFromText('POINT($x1 $y1)', 4326), 900913))");
$tx2 = $dbh->selectrow_array("select ST_X(ST_transform(ST_GeomFromText('POINT($x2 $y2)', 4326), 900913))");
$ty2 = $dbh->selectrow_array("select ST_Y(ST_transform(ST_GeomFromText('POINT($x2 $y2)', 4326), 900913))");
my $cntr = 0;
print("// Note: this file has been autogenerated by $0\n");
print("var FAUGeoJSON = {\n");
print("  \"type\": \"FeatureCollection\",\n");
print("  \"features\": [\n");
foreach $table ('planet_osm_line', 'planet_osm_polygon') {
  my $sth = $dbh->prepare("select osm_id, way, building, 'tower:type', name, tags"
                        . " from $table where"
                        . "   (building is not null or (tags->'building:part') is not null)"
                        . "   and way && ST_MakeEnvelope($tx1, $ty1, $tx2, $ty2)");
  unless ($sth->execute()) {
    print(STDERR "Sorry, database query exploded.!\n");
    exit(1);
  }
  my $sth2 = $dbh->prepare("select ST_X(points) as x, ST_Y(points) as y"
                         . " from (select ST_astext((ST_dumppoints(ST_transform(?, 4326))).geom) as points) as points");
  while ($row = $sth->fetchrow_hashref()) {
    my $hstoredec;
    if (defined($row->{'tags'})) {
      $hstoredec = Pg::hstore::decode($row->{'tags'});
    }
    my $height = fetchlastofhr(1, $hstoredec, 'levels', 'building:levels');
    $height = $height * 2.5;
    $height = fetchlastofhr($height, $hstoredec, 'height', 'building:height');
    $height = sprintf("%.1f", $height);
    my $minheight = fetchlastofhr(0, $hstoredec, 'min_levels', 'building:min_levels');
    $minheight = $minheight * 2.5;
    $minheight = fetchlastofhr($minheight, $hstoredec, 'min_height', 'building:min_height');
    $minheight = sprintf("%.1f", $minheight);
    my $wallcolor = fetchlastofhr(undef, $hstoredec, 'building:color', 'building:colour');
    my $roofcolor = fetchlastofhr(undef, $hstoredec,
                                  'roof:color', 'roof:colour', 'building:roof:color', 'building:roof:colour');
    my $roofshape = fetchlastofhr(undef, $hstoredec, 'roof:shape', 'building:roof:shape');
    my $roofheight = fetchlastofhr(undef, $hstoredec, 'roof:height', 'building:roof:height');
    $cntr++;
    print("  {\n");
    print("    \"type\": \"Feature\",\n");
    print("    \"id\": $cntr,\n");
    print("    \"geometry\": {\n");
    print("      \"type\": \"Polygon\",\n");
    print("      \"coordinates\": [[\n");
    unless ($sth2->execute($row->{'way'})) {
      print(STDERR "Sorry, decoding the way data exploded.\n");
      exit(1);
    }
    my ($onex, $oney);
    while (($onex, $oney) = $sth2->fetchrow_array()) {
      print("        [ $onex, $oney ],\n");
    }
    print("      ]]\n");
    print("    },\n");
    print("    \"properties\": {\n");
    print("       \"height\": $height,\n");
    print("       \"min_height\": $minheight,\n");
    if (defined($wallcolor)) {
      print("       \"wallColor\": \"$wallcolor\",\n");
    }
    if (defined($roofcolor)) {
      print("       \"roofColor\": \"$roofcolor\",\n");
    }
    if (defined($roofshape)) {
      print("       \"roofShape\": \"$roofshape\",\n");
    }
    if (defined($roofheight)) {
      $roofheight = sprintf("%.1f", $roofheight);
      print("       \"roofHeight\": \"$roofheight\",\n");
    }
    print("    }\n");
    print("  },\n");
  }
  $sth2->finish();
  undef($sth2);
  $sth->finish();
  undef($sth);
}
print("  ]\n");
print("};\n");
