#!/usr/bin/perl -w
# $HeadURL: file:///afs/sipb.mit.edu/contrib/weather/SVNRep/tools/StationDB.pm $
# $Id: StationDB.pm 17 2007-09-18 21:57:29Z foley $
# Perl module for loading the station information
# By Joe Foley<foley@mit.edu>

#TODO:
# 1. Add capability to decompress on the fly if the
#    uncompressed version is not available

package StationDB;
use strict;

use Data::Dumper;
use Carp;


sub new {
    my $class = shift;
    my $self = { 
	DB => undef,
	stationfile => undef,
	def_field => "WBAN Number",
	path => undef,
	@_,  # get arguments passed
    };
    bless $self, $class;
    $self->init();
    return($self);
}

sub init {
    my $self = shift;

# lets see where we're at
    my $pwd = `pwd`;  chomp($pwd);
    my $basedir = "$pwd";
    if($pwd =~ m|^/afs/sipb(.mit.edu)?/contrib/weather|) {
	$basedir = "/afs/sipb.mit.edu/contrib/weather";
    }
    if($pwd =~ m|(.*/weather)|) {
	$basedir = "$1";
    }
    
    my $uncompdir = "$basedir/uncompressed";
    opendir(DH, $uncompdir);
    # we want the last directory
    my @dirs = readdir(DH);
    my $lastdir = $dirs[scalar(@dirs)-1];

    my $smartpath = "$uncompdir/$lastdir/station.txt";

    my $stationfile = shift || $self->{stationfile} || $smartpath;
    $self->{stationfile} = $stationfile;

    print "Loading station information from $stationfile\n";
    open(STATIONS, $stationfile)
	or croak "Error:  Unable to read stationfile \"$stationfile\": $!\n";

    $_ = <STATIONS>; chomp($_);
    my @headers = split(/\|/, $_);
    #print @headers;


    my $DB = {};
    while(<STATIONS>) {
	chomp;
	my @line = split(/\|/, $_);

	my $tmp = {};
	foreach(@headers) {
	    my $header = $_;
	    my $val = shift(@line);
	    $tmp->{$header} = $val;
	}
#	print Data::Dumper->Dump([$tmp], [qw($tmp)]);
	my $key = $tmp->{$self->{def_field}};
	$DB->{$key} = $tmp;
    }

#    print Data::Dumper->Dump([$DB], [qw($DB)]);
    $self->{DB} = $DB;
}

sub search {
    my $self = shift;
    my $searchval = shift or confess "Error:  No search value.";
    my $searchfield = shift || "Call Sign";
    my $returnfield = shift || $self->{def_field};

    # we can use a slow search alg, we don't need to do this often
    while(my ($wban,$rec) = each %{$self->{DB}}) {
	$rec->{$searchfield} eq $searchval
	    and return ($rec->{$returnfield}); 
    }
    return(undef);
}

sub get {
    my $self = shift;
    my $wban = shift;
    return($self->{DB}->{$wban});
}


sub test {
    # small
    my $self = StationDB->new(stationfile=>"teststations.txt");
#    print Data::Dumper->Dump([$self],[qw($self)]);
    my $laa = $self->get("03013");
    print Data::Dumper->Dump([$laa],[qw($laa)]);
    my $gcn = $self->search("GCN");
    print "gcn is $gcn\n";

    #real
    my $self2 = StationDB->new();
    print Data::Dumper->Dump([$self2],[qw($self2)]);
    $laa = $self2->get("03013");
    print Data::Dumper->Dump([$laa],[qw($laa)]);
    $gcn = $self2->search("GCN");
    print "gcn is $gcn\n";

    
}


1;
