package App::EventStreamr::DVswitch::Roles::MixerWait;

use v5.010;
use strict;
use warnings;
use Method::Signatures 20140224; # libmethod-signatures-perl
use IO::Socket::INET;

use Moo::Role; # libmoo-perl

# ABSTRACT: Wait for DVswitch Mixer to Start

our $VERSION = '0.5'; # VERSION: Generated by DZP::OurPkg:Version


requires 'run_stop','status','config','id','type';

method _test_port() {
  my $state;
  my $sock = new IO::Socket::INET ( PeerAddr => $self->{config}{mixer}{host},
                                    PeerPort => $self->{config}{mixer}{port},
                                    Proto    => 'tcp'
                                  );
  if ($sock) {
    $state = 1;
    $sock->close;
  } else {
    $state = 0;
  }
  return $state;
}

method _dvswitch_started() {
  # TODO: Not 100% happy with this, but DVswitch likes to accept
  # connections before it's ready to accept them...
  if (! $self->config->dvswitch_running) {
    $self->status->waiting($self->{id},$self->{type},"waiting_dvswitch") if ((time % 10) == 0 );
    return 0 if (! $self->_test_port());
    
    # Give DVswitch time to settle.
    sleep 1;
    $self->config->dvswitch_running('1');
    $self->info("DVswitch found running");
    return 1;
  } else {
    return 1;
  }
}

around 'run_stop' => sub {
  my $orig = shift;
  my $self = shift;
  
  if ( $self->_dvswitch_started() ) {
    $orig->($self);
  } 
};

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

App::EventStreamr::DVswitch::Roles::MixerWait - Wait for DVswitch Mixer to Start

=head1 VERSION

version 0.5

=head1 SYNOPSIS

This is a role wraps around the 'run_stop' of a process.

=head1 DESCRIPTION

This is a Role that can be consumed to ensure the path exists 
before allowing the record process to take place.

It requires a 'run_stop' method, so really should only be consumed
by processes that extend L<App::EventStreamr::Process>.

=head1 AUTHOR

Leon Wright < techman@cpan.org >

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by Leon Wright.

This is free software, licensed under:

  The GNU Affero General Public License, Version 3, November 2007

=cut
