package RPS::Price::Command::Delete;
use strict;
use warnings;

use lib '/app/tools/rps/lib';
use RPS::Price::Form;
use RPS::Price::Command::Edit;
use RPS::Price::Command::List;

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

use RPS::Command;
use base 'RPS::Command';

sub cmd  { return 'delete'; }
sub area { return 'price'; }

use constant kTemplate => "/app/tools/rps/templates/price/index.xsl";

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

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

    my $id = $self->getParam('PriceID');
    if ( !$id ) {
        my $command = RPS::Price::Command::List->new();
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }

    my $price = RPS::Price::Price->new( priceID => $id );

    if ( $price->InUse() || !$price->delete() ) {
        my $errorMsg = RPS::Message->new( type => "error", code => Common::FormObject::kErrDelete );
        my %editParams = (
            PriceID => $id,
            msg     => $errorMsg->toString(),
        );
        my $command = RPS::Price::Command::Edit->new(%editParams);
        return RSApache::Response::Redirect->new( $command->getRedirect() );
    }

    # else redirect to the List command
    my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessDelete );
    my $command = RPS::Price::Command::List->new( msg => $successMessage->toString() );

    return RSApache::Response::Redirect->new( $command->getRedirect() );
}

1;
