#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package Raptor::Tracker::Command::ForceSplit;
use strict;
use warnings;

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

use lib '/app/tools/rps/lib';
use RPS::File::File;

use lib '/app/tools/raptor/lib';
use Raptor::Tracker::Command::Main;

use Raptor::Command;
use base 'Raptor::Tracker::Command::Base';

sub cmd  { return "forcesplit"; }
sub area { return "tracker"; }

use constant kTemplate => '/app/tools/raptor/templates/tracker.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 $file_id     = $self->getParam("file");
    my $periodParam = $self->getParam('period');
    my $pageParam   = $self->getParam('page');

    my $file = RPS::File::File->new( file_id => $file_id );
    assert($file);

    # must still be open
    # shouldn't be able to get to here from the UI, so return undef
    assert( $file->FileStatus != File::File::STATUS_CLOSED );

    my $submit = $self->getParam("forceSubmit");
    if ($submit) {

        # split the file
        my $new_file = $file->Split();
        if ($new_file) {
            $self->{xml}->{NewFile} = $new_file->GetObjectXML();
            my $success = $file->FinishImport();

            if ($success) {

                # Redirect back to the main page with a success message
                #
                my %showParams = (
                    period => $periodParam,
                    page   => $pageParam,

                    #                    msg => $successMessage->toString(),
                );
                my $command = Raptor::Tracker::Command::Main->new(%showParams);
                return RSApache::Response::Redirect->new( $command->getRedirect() );
            }

            $self->addMessageXML( type => "error", code => "finish_failed" );
        } else {
            $self->addMessageXML( type => "error", code => "split_failed" );
        }
    }

    $self->{xml}->{File} = $file->GetObjectXML();

    my $period = new Period::RoyaltyPeriod();
    if ( !$periodParam ) {
        $period->LoadCurrent();
    } else {
        $period->Load( period_id => $periodParam );
    }

    $self->doFileListing($period);
    $self->{xml}{Report}{Period} = $period->GetObjectXML();
    $self->setExceptionsFileStatus();

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

    return $response;
}

1;
