package BookPub::Admin::Command::UpdateReportConfig;
use strict;
use warnings;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::ReportConfig;
use BookPub::Admin::Command::ListReportConfig;
use base 'BookPub::Command';

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

sub cmd      { return 'update_report_config'; }
sub area     { return 'admin'; }
sub pageName { return 'Report Configuration Options'; }

sub execute {
    my $self = shift;

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

    my $rID = $self->getParam('rid') || $self->getParam('report_config_id');
    my @columns = split( /:/, $self->getParam('col_order') );
    my $mode = $self->getParam('mode') || 'update';
    my $msgCode = Common::FormObject::kSuccessFormSubmit;

    if ($rID)    # either update or delete existing
    {
        my $rConf = BookPub::DB::Item::ReportConfig->Lookup( report_config_id => $rID );
        assert($rConf);

        if ( $mode eq 'default' ) {
            my $currDefault = BookPub::DB::Item::ReportConfig->Lookup( is_default => 'Y' );
            if ($currDefault) {
                $currDefault->is_default('N');
                $currDefault->save();
            }

            $rConf->is_default('Y');
            $rConf->save();
            $msgCode = Common::FormObject::kSuccessFormMakeDefault;
        } elsif ( $mode eq 'delete' ) {
            $rConf->delete();
            $msgCode = Common::FormObject::kSuccessDelete;
        } else {
            $rConf->name( $self->getParam('name') );

            #$rConf->file_type($self->getParam('file_type'));
            $rConf->delimiter( $self->getParam('delimiter') );
            $rConf->columns( \@columns );
            $rConf->save();
        }
    } else    # save new record
    {
        # If this is going to be the first (or only) report config, we'll make it the default.
        #
        my $defaultFlag = 'N';
        my $allConfigs  = BookPub::DB::Item::ReportConfig->GetAll();
        if ( 0 == $allConfigs->totalSize() ) {
            $defaultFlag = 'Y';
        }

        my $rConf = BookPub::DB::Item::ReportConfig->Create(
            name => $self->getParam('name'),

            #file_type   => $self->getParam('file_type'),
            delimiter  => $self->getParam('delimiter'),
            columns    => \@columns,
            is_default => $defaultFlag,
        );
        $rConf->save();
    }

    my $successMessage = RSApache::Message->new(
        type => 'success',
        code => $msgCode,
    );
    my $command = BookPub::Admin::Command::ListReportConfig->new( msg => $successMessage->toString() );

    if ( $mode eq 'update' ) {
        return RSApache::Response::JSON->new( { status => 'success', redirect => $command->getRedirect() } );
    }

    # else

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

1;
