#!/usr/bin/perl -w

use lib 'lib';
use warnings;
use strict;

use Getopt::Long qw/:config no_auto_abbrev no_ignore_case bundling pass_through/;
use Pod::Usage;
use Pye;
use JSON::MaybeXS qw/JSON/;
use Term::ANSIColor;
use Text::SpanningTable;

=head1 NAME
 
pye - Inspect logs generated by Pye

=head1 SYNOPSIS

In the command line:

	# show list of latest 10 sessions
	$ pye -b MongoDB

	# show complete log for a specific session ID (say "123")
	$ pye -b MongoDB -S 123

	# log a message for a specific session ID (say "123") with complex data
	$ pye -b MongoDB -S 123 -m "some log message" -D '{ "some": "data" }'
 
=head1 DESCRIPTION

C<pye> is a command line utility for reading and inspecting logs generated by
the L<Pye> logging system. It allows viewing sessions in the log, reading the
entire log of a session, and even adding messages and data to the log.

The utility is meant to be used via shell aliases specific to a certain application
and/or backend, to make it fast and easy to view the log. For example, say I have
an application called "myapp", and another one called "myscript", which save logs
to the same MongoDB database running on a remote server, but to different collections.
I might create the following bash aliases:

	alias myapplog='pye -b MongoDB -d logs -c myapp_logs -H logserver'
	alias myscriptlog='pye -b MongoDB -d logs -c myscript_logs -H logserver'

Then, I can easily inspect the log:

	myapplog                # will list latest sessions in the log
	myapplog -s abcde       # will display the complete log for session 'abcde'

=head1 OPTIONS

The following options are supported by C<pye>. Options marked "Backend-specific"
are not strictly required by C<pye>, but I<may> be required by the backend used.
You need to refer to the documentation of the specific backend to learn more about
the options.

Different backends may support more options than the basic ones described here. C<pye>
passes any option it doesn't recognize to the backend, but these options I<must> be
provided in full form, e.g. C<--find_master 1> or C<--find_master=1>. Refer to your
backend of choice for more information.

=head2 -b, --backend

I<Required>.

The C<Pye> backend to use. For example, C<MongoDB> for L<Pye::MongoDB>.

=head2 -t, --type

I<Backend-specific>.

The database system to use, only for backends that support different database systems.
L<Pye::SQL>, for example, supports MySQL, PostgreSQL and SQLite.

=head2 -H, --host

I<Backend-specific>.

The database host.

=head2 -p, --port

I<Backend-specific>.

The database port.

=head2 -d, --database

I<Backend-specific>.

The name of the database. Defaults to "logs".

=head2 -T, -c, --collection, --table

I<Backend-specific>.

The name of the table or collection where log messages are stored. Defaults to
"logs". C<-c> and C<--collection> are aliases for C<--table>, the option sent to
the backend will be called C<table>.

=head2 -s, -S, --session_id

I<Optional>.

The session ID to display or log a message for.

=head2 -m, --message

I<Optional>.

The message to log to the database (requires session ID to be supplied too).

=head2 -D, --data

I<Optional>.

A JSON string to attach to the message.

=head2 -u, --username

I<Backend-specific>.

The username to connect to the database with.

=head2 -p, --password

I<Backend-specific>.

The password to connect to the database with.

=cut

my ($help, $backend, %options);

my $r = GetOptions(
	'h|?|help'				=> \$help,
	'b|backend=s'			=> \$backend,
	't|type:s'				=> \$options{db_type},
	'H|host:s'				=> \$options{host},
	'p|port:i'				=> \$options{port},
	'd|database:s'			=> \$options{database},
	'T|c|collection|table:s'	=> \$options{table},
	's|S|session_id:s'		=> \$options{session_id},
	'm|message:s'			=> \$options{message},
	'D|data:s'				=> \$options{data},
	'u|username:s'			=> \$options{username},
	'p|password:s'			=> \$options{password}
);

pod2usage(1)
	if $help;

pod2usage(2)
	if $r && !$backend;

# make sure there are no undefined options in %options
foreach (keys %options) {
	delete $options{$_}
		unless defined $options{$_};
}

# add anything we don't recognize to %options too, so that
# it's available to the backend
while (scalar @ARGV) {
	if ($ARGV[0] =~ m/^--/) {
		my ($o, $v) = split(/=/, shift @ARGV);
		$v = shift @ARGV
			unless defined $v;
		$options{$o} = $v;
	}
}

my $pye = Pye->new($backend, %options);
my $json = JSON->new->utf8->allow_nonref->allow_blessed->convert_blessed->pretty;

if ($options{session_id}) {
	if ($options{message}) {
		my $data;
		$data = $json->decode($options{data}) if $options{data};
		$pye->log($options{session_id}, $options{message}, $data);
	}

	my @entries = $pye->session_log($options{session_id});
	if (scalar @entries) {
		foreach my $doc (@entries) {
			print color 'bold red';
			print $doc->{date}, ', ', $doc->{time}, ': ';
			print color 'reset';
			print $doc->{text}, "\n";
			if ($doc->{data}) {
				print color 'green';
				my @rows = split(/\n/, $json->encode($doc->{data}));
				for (my $i = 0; $i <= $#rows; $i++) {
					chomp($rows[$i]);
					print "\t $rows[$i]\n";
				}
			}
			print "\n";
		}
	} else {
		print "Nothing found\n";
	}
} else {
	my @sessions = $pye->list_sessions;

	if (scalar @sessions) {
		print "Latest sessions logged:\n";
		print color 'bold';
		my $t = Text::SpanningTable->new(14, 16, 24); $t->newlines(1);
		print $t->hr('top');
		print $t->row('Date', 'Time', 'Session ID');
		print $t->dhr;
		print color 'reset';
		foreach (@sessions) {
			print $t->row($_->{date}, $_->{time}, $_->{id});
		}
		print color 'bold';
		print $t->hr('bottom');
		print color 'reset';
	} else {
		print "No sessions in log\n";
	}
}

=head1 SEE ALSO

L<Pye>

=head1 BUGS AND LIMITATIONS

Please report any bugs or feature requests to
C<bug-Pye@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Pye>.
 
=head1 SUPPORT
 
You can find documentation for this module by invoking it with
the C<-h> switch:
 
	pye -h
 
=head1 AUTHOR
 
Ido Perlmuter <ido@ido50.net>
 
=head1 LICENSE AND COPYRIGHT
 
Copyright (c) 2013-2015, Ido Perlmuter C<< ido@ido50.net >>.
 
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself, either version
5.8.1 or any later version. See L<perlartistic|perlartistic>
and L<perlgpl|perlgpl>.
 
The full text of the license can be found in the
LICENSE file included with this module.
 
=head1 DISCLAIMER OF WARRANTY
 
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.
 
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
 
=cut