#!/usr/bin/perl -w

# Mapserver interface to Mapblast. Incomplete and kludgy, but works.
# 	var BURL="/pub/agent.dll?qscr=mrdt&ID=3XNsF.&CenP=53.344030,-6.261455&Lang=WLD0409&Alti=";
package MapServer::MapBlast;

use MapServer;
@ISA = "MapServer";

use LWP::UserAgent;

my $MAPCACHE = "mb-cache";
my $SCALE = 20000;
$MAPCACHE = "$MAPCACHE/$SCALE";

sub xscale() {
  return 65 / 0.002 * ( 10000 / $SCALE );
}

sub yscale() {
  return -114 / 0.006 * ( 10000 / $SCALE );
}

sub mag() {
  warn "not implemented\n";
}

sub fetchmap( @ ) {
  my $self = shift;
  my ( $latitude, $longitude ) = @_;
  my $filename;
  -d "$MAPCACHE" || mkdir "$MAPCACHE", 0755;
  $filename = "cache_$ {latitude}_$ {longitude}.gif";

  # First, check if we have a map that covers this area
  opendir( CACHEDIR, $MAPCACHE );
  my @files = grep /^cache/, readdir( CACHEDIR );
  closedir( CACHEDIR );

  for my $f ( @files ) {
	my ( $lat, $long ) = $f =~ m/cache_(.*?)_(.*?)\.gif$/;
	if (( $latitude > ( $lat - ( 0.005 * $SCALE / 10000 ))) &&
		( $latitude < ( $lat + ( 0.005 * $SCALE / 10000 ))) &&
		( $longitude > ( $long - ( 0.005 * $SCALE / 10000))) &&
		( $longitude < ( $long + ( 0.005 * $SCALE / 10000)))) {
		  return "$MAPCACHE/$f";
	}
  }

  return undef unless $self->online();

  $filename = "$MAPCACHE/$filename";

  my $ua = new LWP::UserAgent;
  $ua->agent( "GeekToy/0.1" . $ua->agent );
  $ua->env_proxy();
#  my $url = "http://www.maplast.com/gif?";
#  $url .= "&CT=" . $latitude . ":" . $longitude . ":" . $SCALE;
#  $url .= "&IC=$latitude:$longitude:10:"; # 10 means no icon.
#  $url .= "&FAM=myblast";
#  $url .= "&W=640&H=480";
#  $url .= "&MA=2";
  # http://www.mapblast.com/(z2dk5bqyi3okqx55lhmd4vzz)/MPSvc.aspx?MPMtd=M&L=EUR0809&C=48.6%2c6.6&A=7000&S=405%2c320&PN=1943281943&P=|292d|
  my $url = "http://www.expedia.com/pub/agent.dll?qscr=mrdt&ID=3XNsF.";
  $url .= "&CenP=$latitude,$longitude";

  my $req = new HTTP::Request
	GET => $url;
  my $res = $ua->request( $req );
  if ( $res->is_success ) {
	open( FOO, "|giftopnm |ppmchange '#ffffcc' '#ffffff' | ppmtogif -quiet -transparent '#ffffff' >$ {filename}" );
	binmode( FOO );
	syswrite( FOO, $res->content, length( $res->content ));
	close( FOO );
  } else {
      print "failed (" . $res->code . ")\n";
	return undef;
  }

  return $filename;
}

1;
