package Cross::Storage;

use warnings;
use strict;

use Cross::CouchDB;
use JSON::Any;

our $VERSION = '0.01';

sub new {
	my ($class,$args) = @_;
	my $self = bless {}, $class;

	$self->package($args->{'package'});

	my $db = Cross::CouchDB->new('127.0.0.1', '5984');
	$self->db($db);

	return $self;
}

sub db {
	my $self = shift;

	$self->{'db'} = shift if @_;
	$self->{'db'};
}

sub package {
	my $self = shift;

	$self->{'package'} = shift if @_;
	$self->{'package'};
}

sub store {
	my ($self,$t,$data) = @_;

	foreach (keys %$data) {
		$self->store_r($t,$_, $data->{$_});
	}
}

sub store_r {
	my ($self,$t,$r,$value) = @_;
	$r = lc($r);

	my $j = JSON::Any->new;
	my $url = $self->__build_url;
	my $data = {};
	if ($self->{db}->has($url)) {
		$data = $j->decode($self->{db}->get($url));
	}

	if ($data->{$r}) {
		my $mod = 'Cross::Inspector::'.$t;
		eval "use $mod";
		my $i = eval "$mod->new";
		$value = $i->join($data->{$r}, $value);
	}

	$data->{$r} = $value if $value;

	my $json = $j->encode($data);
	$self->{db}->put($url, $json);
}

sub retrieve {
	my ($self,$t) = @_;

	my $j = JSON::Any->new;
	my $url = $self->__build_url;
	my $r = $self->{db}->get($url);
	my $data = {};

	$data = $j->decode($r) if ($r);

	if ($data) {
		foreach (keys %$data) {
			if ($_ =~ /^_/) {
				delete $data->{$_};
				next;
			}
			unless (ref $data->{$_} eq 'HASH') {
				$data->{$_} = { 'value' => $data->{$_}, 'attrs' => {}};
			}
		}
	}

	return $data;
}

sub __build_url {
	my ($self) = @_;

	'cross/'.$self->package;
}

sub list_packages {
	my ($self,$t) = @_;

	my $j = JSON::Any->new;
	my $data = $j->decode($self->{db}->get('cross/_all_docs'));

	my @list;
	foreach (@{$data->{'rows'}}) {
		push @list, $_->{'key'};
	}

	return [@list];
}

=head1 AUTHOR

Nuno Carvalho, C<< <smash at cpan.org> >>

=head1 BUGS

Please report any bugs or feature requests to C<bug-cross-inspector at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Cross-Inspector>.  I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.




=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Cross::Storage


You can also look for information at:

=over 4

=item * RT: CPAN's request tracker

L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Cross-Storage>

=item * AnnoCPAN: Annotated CPAN documentation

L<http://annocpan.org/dist/Cross-Storage>

=item * CPAN Ratings

L<http://cpanratings.perl.org/d/Cross-Storage>

=item * Search CPAN

L<http://search.cpan.org/dist/Cross-Storage/>

=back


=head1 ACKNOWLEDGEMENTS


=head1 LICENSE AND COPYRIGHT

Copyright 2010 Nuno Carvalho.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See http://dev.perl.org/licenses/ for more information.


=cut

1; # End of Cross::Storage
