#------------------------------------------------------------
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package BookPub::Market::Command::DownloadReport;
use strict;
use warnings;

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use RSApache::Response::DownloadStream;
use Common::Assert;

use lib '/app/tools/bookpub/lib';
use BookPub::RDAS::Form::ProductMonitor::ProductMonitorAlertList;
use BookPub::Market::Command::Report;

use base 'BookPub::Command';

sub cmd      { return "download"; }
sub area     { return "market"; }
sub pageName { return 'Download Alerts'; }

use constant kTemplate => "/app/tools/bookpub/templates/market/report.xsl";

sub execute {
    my ($self) = @_;

    # Give any inherited methods the first crack at this.
    # (This checks for login and basic access permissions).
    #
    my $response = $self->SUPER::execute();
    return $response if $response;

    my $view      = $self->getParam('view');
    my $serviceID = $self->getParam('serviceID');
    my $productID = $self->getParam('productID');
    my $issue     = $self->getParam('issue');

    my $list = new BookPub::RDAS::Form::ProductMonitor::ProductMonitorAlertList(
        view      => $view,
        issue     => $issue,
        serviceID => $serviceID,
        productID => $productID,
    );

    my $report   = $list->asText(',');
    my $filename = 'Alert_Report.csv';

    if ($report) {
        $response = RSApache::Response::DownloadStream->new( $report, 'application/octet-stream', $filename );
    } else {
        my $newCmd = BookPub::Market::Command::Report->new();
        $response = $newCmd->execute();
    }

    return $response;
}

1;
