package Test2::Plugin::IOMuxer::Layer;
use strict;
use warnings;

use Time::HiRes qw/time/;

our $VERSION = '0.000001';

use Test2::Plugin::OpenFixPerlIO;
use IO::Handle;

our %MUXED;
our %MUX_FILES;

sub PUSHED {
    my ($class, $mode, $handle) = @_;
    $handle->autoflush(1);
    bless {}, $class;
}

sub WRITE {
    my ($self, $buffer, $handle) = @_;
    my $time = time;
    my $fileno = fileno($handle);
    my $sync = "TEST2-SYNC-$fileno: $time\n";

    print $handle $buffer;

    my $mh = $MUX_FILES{$MUXED{$fileno}};
    print $mh "START-$sync";
    print $mh $buffer;
    print $mh substr($buffer, -1, 1) eq "\n" ? "+STOP-$sync" : "\n-STOP-$sync";

    return length($buffer);
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Test2::Plugin::IOMuxer::Layer - The PerlIO::via class used by
Test2::Plugin::IOMuxer.

=head1 SOURCE

The source code repository for Test2-Plugin-IOSync can be found at
F<http://github.com/Test-More/Test2-Plugin-IOSync/>.

=head1 MAINTAINERS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 AUTHORS

=over 4

=item Chad Granum E<lt>exodist@cpan.orgE<gt>

=back

=head1 COPYRIGHT

Copyright 2017 Chad Granum E<lt>exodist@cpan.orgE<gt>.

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

See F<http://dev.perl.org/licenses/>

=cut
