#!/usr/bin/perl
#ABSTRACT: DAIA command line client
#PODNAME: daia

use strict;
use warnings;

use utf8;
use Encode;
use CGI qw(:standard);
use LWP::Simple qw(get);
use Data::Dumper;
use JSON;
use DAIA;

# set parameters
my $url = param('url');
$url = shift @ARGV unless $url;
$url ||= "";

my $debug = param('debug') || 0;
$Carp::Verbose = 1 if ($debug);

# TODO: add proxy-parameter to append other parameters to and reuse as URL

my $data = param('data'); # icoming raw data is UTF-8
eval{ $data = Encode::decode_utf8( $data ); };

my $informat  = lc(param('in'));
my $outformat = lc(param('out')) || 'json';

if ($outformat !~ /^(xml|json|rdf|dump)$/) {
    print STDERR "Unsupported output format!\n";
    exit;
}

my $callback = param('callback') || ""; 
$callback = "" unless $callback =~ /^[a-z][a-z0-9._\[\]]*$/i;

my ($error, $daia, @daiaobjs, $eurl);

my $xsd = "daia.xsd"; # TODO: search somewhere else

if( $url !~ /^\s*http[s]?:\/\// and not $data ) {
    $url =~ s#^file://##;
    $url = \*STDIN if $url eq '-';
    if (not defined $url or $url =~ /^-(\?|h|-help)$/) {
        print join("",<DATA>)."\n";
        exit;
    }
} else {
    $eurl = $url; # url_encode
    $eurl =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
}

# parse DAIA
if ( $data ) {
    @daiaobjs = eval { DAIA->parse( data => $data, format => $informat ) };
} elsif( $url ) {
    @daiaobjs = eval { DAIA->parse( file => $url, format => $informat ) };
}
if ($@) {
    $error = $@;
    $error =~ s/DAIA::([A-Z]+::)?[a-z_]+\(\)://ig unless $debug;
    $error =~ s/ at .* line.*//g unless $debug;
}

if ( $error ) {
    print STDERR "$error\n";
} else {
    binmode STDOUT, "utf8";
    foreach my $daia (@daiaobjs) {
        if ($outformat eq 'xml') {
            print $daia->xml(xmlns => 1);
        } elsif($outformat eq 'rdf') {
            print JSON->new->pretty->encode($daia->rdfhash());
        } elsif($outformat eq 'dump') {
            print Dumper($daia);
        } elsif($outformat eq 'json') {
            print $daia->json;
        }
    }
    print "\n";
}




=pod

=head1 NAME

daia - DAIA command line client

=head1 VERSION

version 0.35

=head1 DESCRIPTION

You can pass either an URL which will be queried, or a string of serialized
DAIA. The serialization format (JSON or XML) can be specified or it will get
guessed. You can use this as a proxy to convert serialization format or just
show the result in HTML - in this case you can also validate DAIA/XML against
the XML Schema.

=head1 USAGE

To get usage information call this script with C<-?>, C<-h> or C<--help> as 
only parameter. Options can be passed as C<key=value> pairs and the first 
parameter is treated as filename or URL to read from (use '-' for STDIN as
set by default).

  daia input.xml  out=json  # convert to DAIA/JSON (default)
  daia input.json out=xml   # convert to DAIA/XML

=head1 SEE ALSO

See L<Plack::App::DAIA> and L<Plack::App::DAIA::Validator> for DAIA server
implementations. 

=head1 AUTHOR

Jakob Voss

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2011 by Jakob Voss.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut


__DATA__
usage: daia [<URL-or-FILE>] [<OPTIONS>]

Options are passed as key=value pairs. If no 'url' option is set, the
first parameter is used instead. By default reads from STDIN (url=-).

  data=...          use given string instead of URL or file
  out=...           set output format 
      json            DAIA/JSON (default)
      xml             DAIA/XML
      rdf             DAIA/RDF as RDF/JSON
      dump            Perl Dump format
  in=...            set input format (json or xml)
  callback=...      use callback method (if out=json)
  debug=0|1         disable|enable debug information
  -?|-h|--help      show this help
