#!/usr/bin/perl -w
# NAME: getapts.pl
# AIM: QUITE RESTRICTED - Read an airport CSV file, and find airports closest
# to a given lat,lon
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
use Time::HiRes qw( gettimeofday tv_interval );
my $t0 = [gettimeofday];
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
require 'fg_wsg84.pl' or die "Unable to load fg_wsg84.pl ...\n";
require "Bucket2.pm" or die "Unable to load Bucket2.pm ...\n";

# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);


# user variables
my $VERS = "0.0.1 2013-03-02";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $in_lat = 9999;
my $in_lon = 9999;
my $max_list = 10;
my $output_json = 1;
#/** Meters to Nautical Miles.  1 nm = 6076.11549 feet */
my $METER_TO_NM = 0.0005399568034557235;

# ### DEBUG ###
my $debug_on = 1;
#my $def_file = 'C:\GTools\perl\ap1000-icao.csv';
my $def_file = 'C:\GTools\perl\ap1000-ils.csv';
#my $def_lat = 48;
#my $def_lon = 2;
my $def_lat = 49.0097421575;
my $def_lon = 2.562619395;
### program variables
my @warnings = ();
my $cwd = cwd();

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

sub show_warnings($) {
    my ($val) = @_;
    if (@warnings) {
        prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
        foreach my $itm (@warnings) {
           prt("$itm\n");
        }
        prt("\n");
    } else {
        prt( "\nNo warnings issued.\n\n" ) if (VERB9());
    }
}

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings($val);
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

# put least first
sub mycmp_ascend_n5 {
   if (${$a}[5] < ${$b}[5]) {
      return -1;
   }
   if (${$a}[5] > ${$b}[5]) {
      return 1;
   }
   return 0;
}


#icao,name,lat,lon,runways
#40N,"Chester Co G O Carlson",39.978961,-75.8654665,1
#0    1                            2         3        4
#AYPY,"Port Moresby Jacksons Intl",-9.442079,147.2192,2
# sub fg_geo_inverse_wgs_84 {
#    my ($lat1, $lon1, $lat2, $lon2, $az1, $az2, $s) = @_;

sub process_in_file($) {
    my ($inf) = @_;
    if (! open INF, "<$inf") {
        pgm_exit(1,"ERROR: Unable to open file [$inf]\n"); 
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Processing $lncnt lines, from [$inf]...\n");
    my ($line,@arr,$lnn,$i,$icao,$name,$lat,$lon,$rwycnt,$cnt,$az1,$az2,$dist,$ra);
    $lnn = 0;
    my @newarr = ();
    for ($i = 1; $i < $lncnt; $i++) {
        $line = $lines[$i];
        chomp $line;
        $lnn++;
        next if ($lnn < 2);
        @arr = split(",",$line);
        $cnt = scalar @arr;
        if ($cnt < 5) {
            prtw("$lnn: WARNING: [$line] did not split 5+\n");
            next;
        }
        $icao = $arr[0];
        $name = $arr[1];
        $lat  = $arr[2];
        $lon  = $arr[3];
        $rwycnt = $arr[4];
        fg_geo_inverse_wgs_84( $in_lat, $in_lon, $lat, $lon, \$az1, \$az2, \$dist );
        $az1 = (int($az1 * 10) / 10);
        $dist = $dist * $METER_TO_NM;
        $dist = int($dist);
        #             0     1     2    3    4       5     6
        push(@newarr,[$icao,$name,$lat,$lon,$rwycnt,$dist,$az1]);
        ###prt("$icao,$name,$lat,$lon,$rwycnt,$dist on $az1\n");
    }
    $cnt = scalar @newarr;
    prt("Got $cnt distances from $in_lat, $in_lon...\n");
    #               0     1     2    3    4       5     6
    # push(@newarr,[$icao,$name,$lat,$lon,$rwycnt,$dist,$az1]);
    my @sorted = sort mycmp_ascend_n5 @newarr;
    if ($output_json) {
        prt('{"success":true,"source":"'.$pgmname.'","last_updated":"'.lu_get_YYYYMMDD_hhmmss_UTC(time()).
            ' UTC","airports":['."\n");
        for ($i = 0; $i < $cnt; $i++) {
            $ra = $sorted[$i];
            $icao = ${$ra}[0];
            $name = ${$ra}[1];
            $lat  = ${$ra}[2];
            $lon  = ${$ra}[3];
            $rwycnt = ${$ra}[4];
            $dist = ${$ra}[5];
            $az1 = ${$ra}[6];
            $line = '{"icao":'.$icao.',"name":'.$name.',"lat":'.$lat.',"lon":'.$lon;
            $line .= ',"runways":'.$rwycnt;
            $line .= ',"dist_nm":'.$dist;
            $line .= ',"hdg":'.$az1;
            $line .= '}';
            if (($max_list > 0) && ($i > $max_list)) {
                prt("$line\n");
                last;
            }
            $line .= ',' if (($i + 1) < $cnt);
            prt("$line\n");
        }
        prt("]}\n");
    } else {
        for ($i = 0; $i < $cnt; $i++) {
            $ra = $sorted[$i];
            prt(join(",",@{$ra})."\n");
            if (($max_list > 0) && ($i > $max_list)) {
                last;
            }
        }
    }
    #$load_log = 2;
}

#########################################
### MAIN ###
parse_args(@ARGV);
process_in_file($in_file);
my $elapsed = tv_interval ( $t0, [gettimeofday]);
prt( "Ran for $elapsed seconds ...\n" );
pgm_exit(0,"");
########################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if ((length($in_file) ==  0) && $debug_on) {
            $in_file = $def_file;
            prt("Set DEFAULT input to [$in_file]\n");
        }
        if ($in_lat == 9999) {
            $in_lat = $def_lat;
            prt("Set DEFAULT lat to [$in_lat]\n");
        }
        if ($in_lon == 9999) {
            $in_lon = $def_lon;
            prt("Set DEFAULT lon to [$in_lon]\n");
        }
        ### $load_log = 2;
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if (! -f $in_file) {
        pgm_exit(1,"ERROR: Unable to find in file [$in_file]! Check name, location...\n");
    }
    if (($in_lat == 9999)||($in_lon == 9999)) {
        pgm_exit(1,"ERROR: No lat or lon given in command!\n");
    }

}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-file\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 0.\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --lat degs         = Set latitude.\n");
    prt(" --lon degs         = Set longitude.\n");
    prt(" --pos lat,lon (-p) = Set lat and lon.\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");

}

# eof - template.pl
