#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Statement::UKMechanical::McpsText;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Assert;
use Common::Util;
use Common::RSApp;

use lib '/app/tools/rps/lib';
use RPS::Mechanical::UK::UKMechanicalRun;
use RPS::DB::Item::UKMechanicalRun;
use RPS::DB::Item::McpsStatement;
use RPS::Config;


# !!! For now, this package will probably just contain constants and maybe static methods.
# !!! Later on down the road, I'll look at moving the actual code
# !!! that generates the statements into here.
#
sub _BasePath
{
    my ($class) = @_;

    # !!! Use config file 
    #
    my $config = RPS::Config->new();
    my $path = $config->get('uk_mechanical_royalty_statement_dir');
    return $path;
}

sub StatementFileNameFromID
{
    my ($id) = @_;
    assert($id);

    my $run = RPS::DB::Item::UKMechanicalRun->Lookup(uk_mechanical_run_id => $id);
    return StatementFileNameFromDBItem($run);
}


sub StatementFileNameFromDBItem
{
    my ($runDBItem) = @_;
    assert($runDBItem);

    my $runID = $runDBItem->uk_mechanical_run_id;

    my $fileName = "$runID.txt";

    return $fileName;
}

sub PrettyStatementFileNameFromID
{
    my ($id) = @_;
    assert($id);

    my $run = RPS::DB::Item::UKMechanicalRun->Lookup(uk_mechanical_run_id => $id);
    return PrettyStatementFilePathFromDBItem($run);
}


sub PrettyStatementFileNameFromDBItem
{
    my ($runDBItem) = @_;
    assert($runDBItem);

    my $runID = $runDBItem->uk_mechanical_run_id;
    my $cleanRunLabel = _runLabelClean($runID);

    my $fileName = "$cleanRunLabel.txt";

    return $fileName;
}


# This returns the directory in which statement files can be found.
# client_id is optional - if ommitted, we'll use the current client id.
#
sub StatementPathFromRunID
{
    my ($runID, $clientID) = @_;
    assert($runID);

    $clientID = Common::RSApp::GetClientID() unless $clientID;
    my $clientData = Common::DB::Item::Client->Lookup(client_id => $clientID);
    my $clientName = $clientData->client_name_clean;

    return _BasePath(). "/$clientName/$runID/";
}

# Going to create a little ram cache, since this code will often get called in a loop.
#
my %gRunLabel;
sub _runLabelClean
{
    my ($runID) = @_;

    if (! defined $gRunLabel{$runID})
    {
        my $run = RPS::DB::Item::UKMechanicalRun->Lookup(uk_mechanical_run_id => $runID);
        assert($run, "ERROR - runID $runID is invalid");
        
        $gRunLabel{$runID} = RPS::Mechanical::UK::UKMechanicalRun::GenerateFileLabel($run); 
    }

    return $gRunLabel{$runID};
}


1;
