#!perl

our $DATE = '2015-04-03'; # DATE
our $VERSION = '0.02'; # VERSION

use 5.010;
use strict;
use warnings;

use Perinci::CmdLine::Any;

our %SPEC;

$SPEC{validate_with_sah} = {
    v => 1.1,
    summary => 'Validate data with Sah schema',
    description => <<'_',

Can also be used to just normalize a Sah schema and show it (see
`--show-schema`), or generate validator code and show it (see `--show-code`).

_
    args_groups => [
        {rel=>'one_of', args=>[qw/schema schema_file/]}, # XXX req_one_of
        {rel=>'one_of', args=>[qw/data multiple_data/]},
        # {rel=>'depends', args=>[qw/show_linenum/], on_args=>[qw/show_code/]},
    ],
    args => {
        schema => {
            schema=>'any*',
            pos=>0,
        },
        schema_file => {
            schema=>'str*',
            summary => 'Retrieve schema from file',
            description => <<'_',

JSON and YAML formats are supported. File type will be guessed from filename,
defaults to JSON.

_
            cmdline_aliases => {f=>{}},
            'x.schema.entity' => 'filename',
        },
        schema_file_type => {
            schema=>['str*', in=>[qw/json yaml/]],
            summary => 'Give hint for schema file type',
            cmdline_aliases => {t=>{}},
        },
        data => {
            schema => ['any'],
            pos => 1,
        },
        multiple_data => {
            schema => ['array*', of=>'any'],
        },
        return_type => {
            schema=>['str*', in=>[qw/bool str full/]],
            default=>'str',
            cmdline_aliases => {r=>{}},
        },
        show_schema => {
            summary => "Don't validate data, show normalized schema only",
            schema=>['bool', is=>1],
            cmdline_aliases => {s=>{}},
        },
        show_code => {
            summary => "Don't validate data, show generated validator code only",
            schema=>['bool', is=>1],
            cmdline_aliases => {c=>{}},
        },
        show_data_with_result => {
            summary => "Show data alongside with validation result",
            description => <<'_',

The default is to show the validation result only.

_
            schema=>['bool', is=>1],
            cmdline_aliases => {d=>{}},
        },
        compiler => {
            summary => "Select compiler",
            schema=>['str*', in=>[qw/perl js/]],
            default => 'perl',
            cmdline_aliases => {C=>{}},
        },
        show_linenum => {
            summary => 'When showing source code, add line number',
            schema=>['bool', is=>1],
            cmdline_aliases => {l=>{}},
        },
    },
    examples => [
        {
            src => q([[prog]] 'int*' 42),
            src_plang => 'bash',
            summary => 'Should succeed and return empty string',
        },
        {
            src => q([[prog]] 'int*' '"x"'),
            src_plang => 'bash',
            summary => 'Should show an error message because "x" is not int',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' --return-type bool),
            src_plang => 'bash',
            summary => 'Validate multiple data, should return 0, 1, 0',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' -d),
            src_plang => 'bash',
            summary => 'Show data alongside with result, in a table',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' -c -l),
            src_plang => 'bash',
            summary => 'Show validator Perl code only, with line number',
        },
        {
            src => q([[prog]] '["int","min",1,"max",10]' -C js -c -l),
            src_plang => 'bash',
            summary => 'Show validator JS code only, with line number',
        },
        {
            src => q{[[prog]] -f schema1.json '["data"]'},
            src_plang => 'bash',
            summary => 'Load schema from file',
        },
    ],
};
sub validate_with_sah {
    my %args = @_;

    my $schema;
    if (defined $args{schema}) {
        return [400, "Please specify either 'schema' or 'schema_file', not both"] if defined($args{schema_file});
        $schema = $args{schema};
    } elsif (defined $args{schema_file}) {
        my $path = $args{schema_file};
        my $type = $args{schema_file_type};
        if (!$type) {
            if ($path =~ /\b(json)$/i) { $type = 'json' }
            elsif ($path =~ /\b(yaml|yml)$/i) { $type = 'yaml' }
            else { $type = 'json' }
        }
        if ($type eq 'json') {
            require File::Slurper;
            require JSON;
            my $ct = File::Slurper::read_text($path);
            $schema = JSON::decode_json($ct);
        } elsif ($type eq 'yaml') {
            require YAML::XS;
            $schema = YAML::XS::Load($path);
        } else {
            return [400, "Unknown schema file type '$type', please specify json/yaml"];
        }
    } else {
        return [400, "Please specify 'schema' or 'schema_file'"];
    }

    if ($args{show_schema}) {
        require Data::Sah::Normalize;
        return [200, "OK", Data::Sah::Normalize::normalize_schema($schema)];
    }

    my $func;
    {
        no strict 'refs';
        my $c = $args{compiler};
        if ($c eq 'perl') {
            require Data::Sah;
            $func = \&{"Data::Sah::gen_validator"};
        } elsif ($c eq 'js') {
            require Data::Sah::JS;
            $func = \&{"Data::Sah::JS::gen_validator"};
        } else {
            return [400, "Unknown compiler '$c', please specify perl/js"];
        }
    }

    my $v;
    {
        my %opts;
        if ($args{show_code}) { $opts{source} = 1 }
        $opts{return_type} = $args{return_type};
        $v = $func->($schema, \%opts);
    }

    if ($args{show_code}) {
        $v .= "\n" unless $v =~ /\R\z/;
        if ($args{show_linenum}) {
            require String::LineNumber;
            $v = String::LineNumber::linenum($v);
        }
        return [200, "OK", $v, {'cmdline.skip_format'=>1}];
    }

    if (exists $args{data}) {
        if ($args{show_data_with_result}) {
            return [200, "OK", {data=>$args{data}, result=>$v->($args{data})}];
        } else {
            return [200, "OK", $v->($args{data})];
        }
    } elsif ($args{multiple_data}) {
        if ($args{show_data_with_result}) {
            return [200, "OK", [map {{data=>$_, result=>$v->($_)}} @{ $args{multiple_data} }]];
        } else {
            return [200, "OK", [map {$v->($_)} @{ $args{multiple_data} }]];
        }
    } else {
        return [400, "Please specify 'data' or 'multiple_data'"];
    }

    [200, "OK"];
}

my $cli = Perinci::CmdLine::Any->new(
    url => '/main/validate_with_sah',
);
$cli->{common_opts}{naked_res}{default} = 1;
$cli->run;

# ABSTRACT: Validate data with Sah schema
# PODNAME: validate-with-sah

__END__

=pod

=encoding UTF-8

=head1 NAME

validate-with-sah - Validate data with Sah schema

=head1 VERSION

This document describes version 0.02 of validate-with-sah (from Perl distribution App-SahUtils), released on 2015-04-03.

=head1 SYNOPSIS

Usage:

 % validate-with-sah [options] [schema] [data]

Examples:

Should succeed and return empty string:

 % validate-with-sah 'int*' 42

Should show an error message because "x" is not int:

 % validate-with-sah 'int*' '"x"'

Validate multiple data, should return 0, 1, 0:

 % validate-with-sah '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' --return-type bool

Show data alongside with result, in a table:

 % validate-with-sah '["int","min",1,"max",10]' --multiple-data-json '[-4,7,15]' -d

Show validator Perl code only, with line number:

 % validate-with-sah '["int","min",1,"max",10]' -c -l

Show validator JS code only, with line number:

 % validate-with-sah '["int","min",1,"max",10]' -C js -c -l

Load schema from file:

 % validate-with-sah -f schema1.json '["data"]'

=head1 DESCRIPTION

Can also be used to just normalize a Sah schema and show it (see
C<--show-schema>), or generate validator code and show it (see C<--show-code>).

=head1 OPTIONS

C<*> marks required options.

=over

=item B<--compiler>=I<s>, B<-C>

Select compiler.

Default value:

 "perl"

Valid values:

 ["perl","js"]

=item B<--config-path>=I<filename>

Set path to configuration file.

Can be specified multiple times.

=item B<--config-profile>=I<s>

Set configuration profile to use.

=item B<--data-json>=I<s>

See C<--data>.

=item B<--data>=I<s>

=item B<--format>=I<s>

Choose output format, e.g. json, text.

Default value:

 undef

=item B<--help>, B<-h>, B<-?>

Display this help message.

=item B<--json>

Set output format to json.

=item B<--multiple-data-json>=I<s>

See C<--multiple-data>.

=item B<--multiple-data>=I<s>

=item B<--no-config>

Do not use any configuration file.

=item B<--no-naked-res>

When outputing as JSON, add result envelope.

By default, when outputing as JSON, the full enveloped result is returned, e.g.:

    [200,"OK",[1,2,3],{"func.extra"=>4}]

The reason is so you can get the status (1st element), status message (2nd
element) as well as result metadata/extra result (4th element) instead of just
the result (3rd element). However, sometimes you want just the result, e.g. when
you want to pipe the result for more post-processing. In this case you can use
`--naked-res` so you just get:

    [1,2,3]


=item B<--return-type>=I<s>, B<-r>

Default value:

 "str"

Valid values:

 ["bool","str","full"]

=item B<--schema-file-type>=I<s>, B<-t>

Give hint for schema file type.

Valid values:

 ["json","yaml"]

=item B<--schema-file>=I<filename>, B<-f>

Retrieve schema from file.

JSON and YAML formats are supported. File type will be guessed from filename,
defaults to JSON.


=item B<--schema-json>=I<s>

See C<--schema>.

=item B<--schema>=I<s>

=item B<--show-code>, B<-c>

Don't validate data, show generated validator code only.

=item B<--show-data-with-result>, B<-d>

Show data alongside with validation result.

The default is to show the validation result only.


=item B<--show-linenum>, B<-l>

When showing source code, add line number.

=item B<--show-schema>, B<-s>

Don't validate data, show normalized schema only.

=item B<--version>, B<-v>

=back

=head1 ENVIRONMENT

VALIDATE_WITH_SAH_OPT

=head1 FILES

~/validate-with-sah.conf

/etc/validate-with-sah.conf

=head1 COMPLETION

This script has shell tab completion capability with support for several
shells.

=head2 bash

To activate bash completion for this script, put:

 complete -C validate-with-sah validate-with-sah

in your bash startup (e.g. C<~/.bashrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is recommended, however, that you install L<shcompgen> which allows you to
activate completion scripts for several kinds of scripts on multiple shells.
Some CPAN distributions (those that are built with
L<Dist::Zilla::Plugin::GenShellCompletion>) will even automatically enable shell
completion for their included scripts (using C<shcompgen>) at installation time,
so you can immadiately have tab completion.

=head2 tcsh

To activate tcsh completion for this script, put:

 complete validate-with-sah 'p/*/`validate-with-sah`/'

in your tcsh startup (e.g. C<~/.tcshrc>). Your next shell session will then
recognize tab completion for the command. Or, you can also directly execute the
line above in your shell to activate immediately.

It is also recommended to install C<shcompgen> (see above).

=head2 other shells

For fish and zsh, install C<shcompgen> as described above.

=head1 HOMEPAGE

Please visit the project's homepage at L<https://metacpan.org/release/App-SahUtils>.

=head1 SOURCE

Source repository is at L<https://github.com/perlancar/perl-App-SahUtils>.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website L<https://rt.cpan.org/Public/Dist/Display.html?Name=App-SahUtils>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

perlancar <perlancar@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by perlancar@cpan.org.

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
