package App::EventStreamr::Roles::Record;

use v5.010;
use strict;
use warnings;
use Method::Signatures 20140224; # libmethod-signatures-perl
use POSIX 'strftime';
use File::Path 'make_path';
use Proc::ProcessTable; # libproc-processtable-perl

use Moo::Role; # libmoo-perl

# ABSTRACT: A recording role

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


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


method _record_path() {
  if ( ! defined $self->{status}{$self->{id}}{date} || $self->{status}{$self->{id}}{date} != strftime "%Y%m%d", localtime ) {
    $self->{status}{$self->{id}}{date} = strftime "%Y%m%d", localtime;
  
    $self->{status}{$self->{id}}{record_path} = $self->{config}{record_path};

    my %cmd_vars =  (
      room    => $self->{config}{room}, 
      date    => $self->{status}{$self->{id}}{date},
    );

    $self->{status}{$self->{id}}{record_path} =~ s/\$(\w+)/$cmd_vars{$1}/g;
  } 
  
  my $result;
  if ( ! -d "$self->{status}{$self->{id}}{record_path}" ) {
    $self->status->starting($self->{id},$self->{type});
    $result = eval { make_path("$self->{status}{$self->{id}}{record_path}") };
    #TODO: Logging
  } else {
    # TODO: We should check if the path is still writeable.
    # We had a failed disk cause some issues at LCA2014.
    $result = 1;
  }

  return $result; 
}

around 'run_stop' => sub {
  my $orig = shift;
  my $self = shift;
  
  if ( $self->_record_path() ) {
    $orig->($self);
  } else {
    $self->status->threshold($self->{id},'not_writeable');
  }
};

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

App::EventStreamr::Roles::Record - A recording role

=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
