#!/usr/bin/env perl 

use strict;
use warnings;
use Spreadsheet::HTML;

use Safe;
use Pod::Usage;
use Getopt::Long;

eval "use HTML::Display";
our $NO_DISPLAY = $@;

my $generator = Spreadsheet::HTML->new;
my $method    = shift if $generator->can( $ARGV[0] || '' );
$method ||= 'generate';

GetOptions (
    'param=s'   => \my %params,
    'display'   => \my $display,
    'help'      => \my $help,
    'man'       => \my $man,
    'version'   => \my $version,
);
pod2usage( -verbose => 0 ) if $help;
pod2usage( -verbose => 2 ) if $man;

if ($version) {
    print "$_\n" for 
        "   Spreadsheet::HTML version: $Spreadsheet::HTML::VERSION",
        "       HTML::AutoTag version: $HTML::AutoTag::VERSION",
        "Tie::Hash::Attribute version: $Tie::Hash::Attribute::VERSION",
    ;
    exit;
}

my @skip  = qw( fill file art map sep );
my @undef = qw( encodes empty );

my %args;
my $safe = Safe->new;
for my $key (keys %params) {
    next if grep { $key eq $_ } @skip;
    $args{$key} = $safe->reval( $params{$key} );
}

for (@skip)  { $args{$_} = $params{$_} if exists $params{$_}  }
for (@undef) { $args{$_} = undef if exists $params{$_} and $params{$_} eq 'undef' }

if ($display) {
    if ($NO_DISPLAY) {
        warn "please install HTML::Display\n";
    } else {
        HTML::Display::display( $generator->$method( %args ) );
        exit;
    }
}

print $generator->$method( %args ), $/;

__END__
=head1 NAME

mktable - generate an HTML table.

=head1 SYNOPSIS

mktable method [options]

 Options:
   --param          parameters, multiple allowed
   --display        display results via HTML::Display
   --help           list usage
   --man            print man page

Example:

  mktable portrait --param file=data.xls > out.html

  # portrait is default generation method
  mktable --param file=data.xls --param preserve=1 > out.html

  # display output to browser with HTML::Display
  mktable landscape --param data=[[a..d],[1..4],[5..8]] --display

  mktable conway --param data=[1..300] --param wrap=20 --param matrix=1 --display

  mktable sudoku --display

  # banner requires you to install and configure Text::FIGlet
  mktable banner --param text="'hello world'" --param scroll=1 --param bx=1 --display

  # wrap references with quotes:
  mktable --param -r1='{class=>"foo"}'

=head1 OPTIONS

=over 8

=item B<--param>

The params. See perldoc L<Spreadsheet::HTML> for more documentation.

=item B<--display>

Display results to your browser via L<HTML::Display>.

=item B<--help>

Print a brief help message and exits.

=item B<--man>

Prints the manual page and exits.

=item B<--version>

Prints the versions of the core modules used.

=back

=cut
