#---------------------------------------------------------------
# ____                   _ _         ____  _                    
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___ 
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/                            
#
# Copyright (C) 2012 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------


# !!! This is the 'Final' class from ArtistRoyalty.   It assumes that the final product
# is a db table, which is not actually true for label royalties.
#
# I think I may make this a base class, then have two intermediate classes that overload Commit - 
# The DB classes will use mysqlimport, while the output file will just copy it to it's final destination
# (which I belive is on the shared filesystem).

package RPS::LabelRoyalty::Fast::Final;

use strict;
use Data::Dumper;
use File::Path;

use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use lib '/app/tools/raptor/lib';
use Common::RSApp;
use Common::RSDB;
use Common::Assert;
use Common::Log;

use IO::File;

use Common::Log;


# We'll maintain some hashes to store derived class global data.
# The class package will be the hash key.
#
my %gFD;
my %gCurrentID;


sub Init
{
    my ($class, $outputDirectory) = @_;
    assert($outputDirectory, "ERROR - missing outputDirectory");

    assert(! $gFD{$class}, "ERROR - Class is already initialized");


    # !!! For the 'Report' Final classes, we want to create a new file for each payee.
    # !!! So we'll need a mechanism to open a new file discriptor.
    #
    $class->InitFD($outputDirectory);

}

sub InitFD
{
    my ($class, $outputDirectory) = @_;

    $gFD{$class} = $class->WriteFD($outputDirectory);
}


sub WriteFD
{
    my ($class, $dataPath) = @_;

    my $filename = "$dataPath/" . $class->FileName();
    my $fd = IO::File->new("> $filename")
     || die "ERROR: Unable to open $filename: $!";

    binmode($fd, ':utf8');
    return $fd;
}

sub BlankItem
{
    my ($class) = @_;

    my $f = $class->Fields();

    my @array;
    foreach (@$f)
    {
        push @array, 0;
    }
    return \@array;
}


# !!! Overload this, and move this implementation into the 'DB' subclass.
#
sub Commit
{
    my ($class, $dataPath) = @_;

    assert(0, 'overload');
}


# Here's the one remotely clever bit:  We'll write out our state when the line object goes out of scope.
#
sub DESTROY
{
    my ($self) = @_;
    my $class = ref($self);
    my $fd = $gFD{$class};
    $self->_output($fd);
}


sub _output
{
    my ($self, $fd) = @_;
    
    # we certainly don't mean to bring along any newlines or tabs
    foreach (@$self) {s/\n/ /g;}
    foreach (@$self) {s/\t/ /g;}

    print $fd join("\t", @$self) . "\n";
}

1;

