package WebPAC::Output::JSON;

use warnings;
use strict;

use base qw/WebPAC::Common WebPAC::Output Class::Accessor/;
__PACKAGE__->mk_accessors(qw(path));

use Data::Dump qw/dump/;
use JSON;
use File::Slurp;

=head1 NAME

WebPAC::Output::JSON - Create JSON output

=head1 VERSION

Version 0.00

=cut

our $VERSION = '0.00';

=head1 SYNOPSIS

Create JSON output for export into other sistems

=head1 FUNCTIONS

=head2 new

 my $out = new WebPAC::Output::JSON({
 	path => '/path/to/file.js',
 });

Options are:

=over 4

=item path

path to JSON file

=back

=head2 init

  $out->init;

=cut

sub init {
	my $self = shift;
	my $log = $self->_get_logger;

	$log->debug('init');

	$self->{_data} = [];

	return 1;
}


=head2 add

Adds one entry to database.

  $out->add( 42, $ds );

=cut

sub add {
	my $self = shift;

	my ( $id, $ds ) = @_;

	my $log = $self->_get_logger;
	$log->logdie("need id") unless defined $id;
	$log->logdie("need ds") unless $ds;

	$log->debug("id: $id ds = ",sub { dump($ds) });

	push @{ $self->{_data} }, $self->ds_to_hash( $ds, 'display' );

	return 1;
}

=head2 finish

 $out->finish;

=cut

sub finish {
	my $self = shift;

	my $log = $self->_get_logger();

	$log->info("writing JSON output to ", $self->path);
	write_file( $self->path, objToJson( { items => $self->{_data} } ) );

}

=head1 AUTHOR

Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>

=head1 COPYRIGHT & LICENSE

Copyright 2007 Dobrica Pavlinusic, All Rights Reserved.

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

=cut

1; # End of WebPAC::Output::JSON
