use strict;
use warnings;

package CtrlO::DBIC::Cursor::RowCountStatistics;
use Class::Method::Modifiers;

use CtrlO::DBIC::Cursor::RowCountStatistics::Storage;

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

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

around new => sub {
    my $orig = shift;
    my ($class, $storage, @rest) = @_;
    return $orig->(
        $class,
        CtrlO::DBIC::Cursor::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->(@_);
    $self->_emit_query_complete(scalar(@rows));
    return @rows;
};

before __finish_sth => sub {
    my ($self) = @_;
    my $sql = $self->sth->{Statement};
    $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;
}

1;

=head1 NAME

CtrlO::DBIC::Cursor::RowCountStatistics - Description goes here

=head1 SYNOPSIS

=head1 DESCRIPTION

=head1 AUTHOR

 r.sedlacek@shadowcat.co.uk

=head1 CONTRIBUTORS

None yet - maybe this software is perfect! (ahahahahahahahahaha)

=head1 COPYRIGHT

Copyright (c) 2015 the CtrlO::DBIC::Cursor::RowCountStatistics L</AUTHOR> and L</CONTRIBUTORS>
as listed above.

=head1 LICENSE

This library is free software and may be distributed under the same terms
as perl itself.
