#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Support::ProductDistribution::Command::Redeliver;
use strict;
use warnings;

use lib '/app/tools/support/lib';
use base 'Support::Command::Submit';

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

use lib '/app/tools/rps/lib';
use RPS::Catalog::AlbumSimple;
use RPS::Product::ProductDigitalWithServices;
use RPS::Product::Product;

sub cmd  { return 'redeliver_detail'; }
sub area { return 'cm'; }

use constant kTemplate => "/app/tools/support/templates/cm/redeliver.xsl";

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

    my $response = $self->SUPER::execute();
    return $response if $response;

    my $form = new RPS::Catalog::AlbumSimple( albumID => $self->getParam('AlbumID') );
    $self->{xml}{Form}->{Album} = $form;

    my $products = RPS::DB::Item::ProductDigital->GetByAlbumID( $form->AlbumID );
    my $product = $products->next() if ($products);

    if ( $self->isSubmit() ) {
        $self->{xml}->{Message} = $self->process($product) if ($product);
    }

    $self->{xml}->{Form}->{ProductDigital} = RPS::Product::ProductDigitalWithServices->new( _dbItem => $product );
    $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );

    $response = RSApache::Response::XSLT->new( $self->{xml}, kTemplate );
    return $response;
}

sub process {
    my $self            = shift;
    my $product_digital = shift;

    my @requeueServices  = $self->getRequeueServices();
    my @takedownServices = $self->getTakedownServices();

    my $product = new RPS::Product::Product( productID => $product_digital->product_id );

    assert($product);

    $product->requeueDelivery(@requeueServices)   if (@requeueServices);
    $product->takedownDelivery(@takedownServices) if (@takedownServices);

    return "Update Successful.";
}

sub getRequeueServices {
    my $self = shift;
    my @services;
    my $id;
    my $label;

    my $args = $self->getParams();

    foreach ( keys(%$args) ) {
        ( $label, $id ) = split(/_/);
        push( @services, $id )
          if ( $label && $label eq 'action' && $args->{$_} && $args->{$_} eq 'requeue' && $id );
    }

    return @services;
}

sub getTakedownServices {
    my $self = shift;
    my @services;
    my $id;
    my $label;

    my $args = $self->getParams();

    foreach ( keys(%$args) ) {
        ( $label, $id ) = split(/_/);
        push( @services, $id )
          if ( $label && $label eq 'action' && $args->{$_} && $args->{$_} eq 'takedown' && $id );
    }

    return @services;
}

1;
