use strict;
use warnings;

use Getopt::Long;
use File::Spec;

use Java::Javap::Grammar;
use Java::Javap::Generator;

my $genwith   = 'Std';
my $genoptstr = '';
my $jpcmd     = '';
my $nest;              # output comes to screen at present
my $outdir    = '.';   # output comes to screen at present
my $recurse;  # we can't even make classes yet, this will have to wait

# not yet done:
#   astas - no, make this a Genterator,
#           but do write the backends for YAML and Perl
#   nest
#   recurse

GetOptions(
    'jpcmd|j=s'   => \$jpcmd,
    'genwith|g=s' => \$genwith,
    'genopts|p=s' => \$genoptstr,
    'nest|n'      => \$nest,
    'outdir|d=s'  => \$outdir,
    'help|h'      => \&help,
);

my @genopts = split /\s+/, $genoptstr;

my $class_file = shift or die "usage: $0 [options] class_file\n";

my $parser = Java::Javap::Grammar->new();
my $jenny  = Java::Javap::Generator->get_generator( $genwith, @genopts );

my $decomp = `javap $jpcmd $class_file`;

my $tree   = $parser->comp_unit( $decomp );

my $output = $jenny->generate(
    {
        class_file  => $class_file,
        ast         => $tree,
        javap_flags => $jpcmd,
    }
);

if ( $outdir eq 'STDOUT' ) {
    print $output;
}
else { # put it in a directory

    my $module_dir = $outdir;
    my @subdirs    = split /\./, $class_file;
    my $class_name = pop @subdirs;

    mkdir $module_dir;

    my $file;
    if ( $nest ) {
        foreach my $subdir ( @subdirs ) {
            $module_dir = File::Spec->catdir( $module_dir, $subdir );
            mkdir $module_dir;
        }
    }

    my $file_name = File::Spec->catfile( $module_dir, "$class_name.pm" );

    open my $API_MODULE, '>', $file_name
            or die "Couldn't write to $file_name: $!\n";

    print $API_MODULE $output;

    close $API_MODULE;
}

sub help {
    print <<'EO_Help';
java2perl6 [options] class_file

where options are:

    --jpcmd or -j     a string of command line flags for javap, example:
                      -j '-classpath /some/path'
    --genwith or -g   the name of a Java::Javap::Generator:: module which
                      will make the output, defaults to Std
    --genopts or -p   strings to pass to your -g constructor
    --nest or -n      flag indicates output should go in nested directories
    --outdir or -d    top level directory for output
    --help or -h      this message
EO_Help
    exit;
}
