package Lire::ReportSchedule;

use strict;

use Carp;
use Locale::TextDomain 'lire';

use Lire::DlfSchema;
use Lire::ReportConfig;
use Lire::FilterSpec;
use Lire::FilterExpr;
use Lire::Utils qw/ check_param check_object_param /;
use Time::Local;
use Lire::WeekCalculator;

=pod

=head1 NAME

Lire::ReportSchedule - Object which reprents one periodical report generation.

=head1 SYNOPSIS

  use Lire::ReportJob;
  use Lire::ReportSchedule;

  my $store = Lire::DlfStore->open( 'aStore' );
  my $job = new Lire::ReportJob( "webServer" );
  my $cfg = $store->get_report_config( 'daily_www_report' );
  $job->add_schedule( new Lire::ReportSchedule( 'daily', $cfg );
  $job->run( 'daily', $store );

=head1 DESCRIPTION

Lire::ReportSchedule objects together with Lire::OutputJob objects
make it possible to configure all kind of periodical report
generation. Whereas the Lire::OutputJob is used to represent the
formatting of one generated report, the Lire::ReportSchedule
represents such a generation. It will be use to generate periodically
one XML report in a DlfStore using one report configuration file.

ReportSchedules grouped together in one ReportJob are assumed to
generate compatible reports as far as merging is concerned. The idea
is that previous reports generated in one ReportJob (according to
different schedules) could be used as a data source when the DlfStore
doesn't contain all the DLF records for the whole period. For example,
if you don't keep one year of www DLF in your store, you could still
generate an yearly report using the daily reports generated during the
year.

=head2 new( $period, $cfg );

Creates a new Lire::ReportSchedule that will generates an XML report
using the Lire::ReportConfig $cfg on a $period period.
$period should be one of 'hourly', 'daily', 'weekly', 'monthly' or
'yearly'.

=cut

sub new {
    my ( $class, $period, $cfg ) = @_;

    check_param( $period, 'period', qr/^(hourly|daily|weekly|monthly|yearly)$/,
                 "'period' parameter should be one of 'hourly', 'daily', 'weekly', 'monthly' or 'yearly'" );
    check_object_param( $cfg, 'cfg', 'Lire::ReportConfig' );

    my $self = bless { '_period' => $period,
                       '_cfg' => $cfg,
                       '_output_jobs' => [],
                     }, $class;

    return $self;
}

=pod

=head2 period()

Returns the period of this ReportSchedule.

=cut

sub period { $_[0]{'_period'} };


=pod

=head2 period_range( [ $time ] )

Returns the starting and ending boundaries of the schedule period
which includes $time. (Defaults to now). The ending boundary is
excluded from the period and the starting boundary is included.

=cut

sub period_range {
    my ($self, $time) = @_;

    return Lire::Utils::period_range( $self->{'_period'}, $time || time() );
}

=pod

=head2 report_config( [ $new_cfg ] )

Returns (and optionally change) the Lire::ReportConfig object to
use for this schedule.

=cut

sub report_config {
    my ( $self, $new_cfg ) = @_;

    if ( @_ == 2 ) {
        check_object_param( $new_cfg, 'new_cfg', 'Lire::ReportConfig' );
        $self->{'_cfg'} = $new_cfg;
    }
    return $self->{'_cfg'};
}

=pod

=head2 init_report_config( [ $time ] )

Returns the Lire::ReportConfig object with filters set. A FilterSpec
will have been added to each section of the ReportConfig object which
will restrict the reporting on the period defined for the scedule. The
boundaries of the period are determined according to $time which
defaults to now.

=cut

sub init_report_config {
    my ( $self, $time ) = @_;

    $time ||= time();
    my $cfg = $self->{'_cfg'};

    my $range = $self->period_range( $time );
    foreach my $sect ( $cfg->sections() ) {
        foreach my $spec ( $sect->reports() ) {
            my $field = '$' .
              $spec->schema()->timestamp_field()->name();
            my $time_filter =
              new Lire::FilterExpr::And( 'container' => $spec, );
            my $start =
              new Lire::FilterExpr::Ge( 'container' => $spec,
                                        'arg1' => $field,
                                        'arg2' => $range->[0] );
            my $end = new Lire::FilterExpr::Lt( 'container' => $spec,
                                                'arg1' => $field,
                                                'arg2' => $range->[1] );
            my $expr = [ $start, $end ];
            push @$expr, $spec->filter_spec()
              if $spec->filter_spec();
            $time_filter->expr( $expr );
            $spec->filter_spec( $time_filter );
        }
    }

    return $cfg;
}

=pod

=head2 add_output_jobs( $job, ... )

Adds one or more Lire::OutputJob to the ReportSchedule object.

=cut

sub add_output_job {
    my ( $self, @jobs ) = @_;

    croak "missing one or more 'output_job' parameters"
      unless @jobs;

    foreach my $job ( @jobs ) {
        check_object_param( $job, 'output_job', 'Lire::OutputJob' );
        push @{$self->{'_output_jobs'}}, $job;
    }

    return;
}

=pod

=head2 output_jobs()

Returns the Lire::OutputJobs related to this object.

=cut

sub output_jobs {
    return @{$_[0]{'_output_jobs'}};
}

=pod

=head2 run( $store, $report_job, [$time]  )

Generate a XML report and save it in the $store Lire::DlfStore. The
report will be generated either using the DlfStreams or previously
generated reports. Preferences is giving to generating the report
using the Dlf data For more details, consult the documentation
of find_report_source() in Lire::DlfStore(3pm).

The period for which the report will be generated is done using the
$time parameter which defaults to now. For example, a 'daily' report
will generate a report for the whole day (midnight-midnidht based on
the day that $time represents).

Once the report is generated, all registered OutputJob will be run
with the new report.

=cut

sub run {
    my ( $self, $store, $report_job, $time ) = @_;

    my $source = $store->find_report_source( $report_job, $self, $time );
    return if $source->{'source'} eq 'none';

    my $cfg = $self->init_report_config( $time );
    my $report;
    if ( $source->{'source'} eq 'merging' ) {
        $report = $cfg->merge_report_files( @{$source->{'reports'}} );
    } else {
        $report = $cfg->generate_report( $store );
    }
    $report->timespan_period( $self->period() );
    $report->timespan_start( $source->{'start'} );
    $report->timespan_end( $source->{'end'} );

    my $report_file = $store->put_report( $report_job, $self, $report );
    foreach my $job ( $self->output_jobs() ) {
        $job->run( $report_file, $time );
    }
    return;
}

sub new_from_config {
    my ( $pkg, $dict ) = @_;

    $dict = $dict->Lire::Config::Dictionary::as_value();
    my $sched = new Lire::ReportSchedule( $dict->{'period'},
                                          $dict->{'report_config'});
    $sched->add_output_job( @{$dict->{'output_jobs'}} )
      if @{$dict->{'output_jobs'}};

    return $sched;
}

1;

__END__

=pod

=head1 SEE ALSO

Lire::DlfStore(3pm) Lire::DlfConverter(3pm)

=head1 AUTHOR

  Francis J. Lacoste <flacoste@logreport.org>

=head1 VERSION

$Id: ReportSchedule.pm,v 1.17 2006/07/23 13:16:29 vanbaal Exp $

=head1 COPYRIGHT

Copyright (C) 2004 Stichting LogReport Foundation LogReport@LogReport.org

This file is part of Lire.

Lire is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html.

=cut

