use strict;
use warnings;

package DBIx::Class::RowCountStatistics;
use Class::Method::Modifiers;

use DBIx::Class::RowCountStatistics::Storage;

use parent 'DBIx::Class::Storage::DBI::Cursor';

our $VERSION = '0.000001'; # 0.0.1
$VERSION = eval $VERSION;

# Wrap the original ::Storage::DBI we received so we can extract data
# from it's usage by the Cursor.
around new => sub {
    my $orig = shift;
    my ($class, $storage, @rest) = @_;

    return $orig->(
        $class,
        DBIx::Class::RowCountStatistics::Storage->new($storage),
        @rest,
    );
};

after next => sub {
    my ($self) = @_;
    $self->{_ctrlo_rcs_count}++
        unless $self->{_done};
};

around all => sub {
    my $orig = shift;
    my ($self) = @_;

    my @rows = $orig->(@_);

    # ->all does its own finalization, so we fire the complete event
    # right here.
    $self->_emit_query_complete(scalar(@rows));
    return @rows;
};

before __finish_sth => sub {
    my ($self) = @_;

    $self->_emit_query_complete($self->{_ctrlo_rcs_count} || 0);
};

sub _emit_query_complete {
    my ($self, $count) = @_;

    $self->storage->debugobj->query_complete(
        $count,
        $self->storage->_cached_sql,
        # TODO pass bind params
    ) if $self->storage->debug
        and $self->storage->debugobj->can('query_complete');
}

1;

=head1 NAME

DBIx::Class::RowCountStatistics - Provide row-count statistics

=head1 SYNOPSIS

    my $schema = Schema->connect(
        $dsn, $username, $password,
        {},
        { cursor_class => 'DBIx::Class::RowCountStatistics' },
    );

=head1 WARNING

This module overrides internal L<DBIx::Class> functionality, and might
break with every update.

=head1 DESCRIPTION

This L<DBIx::Class::Storage::DBI::Cursor> subclass allows you to log the
number of rows that were fetched through the cursor.

B<Warning>: This module currently lies on L<DBIx::Class> internals and
might break with an update.

=head1 DEBUG OBJECT METHODS

=head2 query_complete (optional)

If available on the L<DBIx::Class::Storage/debugobj>, this method will be
called with the following signature:

    sub query_complete {
        my ($self, $row_count, $sql) = @_;
        ...
    }

=head1 SPONSORS

Development of this module was sponsored by

=over

=item * Ctrl O L<http://ctrlo.com>

=back

=head1 AUTHOR

 r.sedlacek@shadowcat.co.uk

=head1 CONTRIBUTORS

None yet.

=head1 COPYRIGHT

Copyright (c) 2015 the DBIx::Class::RowCountStatistics L</AUTHOR> and L</CONTRIBUTORS>
as listed above.

=cut
