package Support::ArtistRoleMap::Command::Import;

use Data::Dumper;
use IO::File;
use POSIX qw(tmpnam);

use strict;
use lib '/app/tools/common/lib';
use Common::Log;

use lib '/app/tools/support/lib';
use Support::Command;
use Support::ArtistRoleMap::Importer;

use base 'Support::Command';

sub cmd  { return 'import_artist_role_map' }
sub area { return 'cm' }

use constant kTemplate => "/app/tools/support/templates/artist_role_map/show.xsl";

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

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

    # Upload the file to a _temporary_ file location.
    #
    my $fileName   = $self->getParam("fileUpload");
    my $filehandle = $self->getCGI()->upload("fileUpload");
    die "ERROR - missing filehandle" unless $filehandle;

    Common::Log::Debug("IMPORTING file $fileName\n");

    # Attempt to import it.
    # We don't need an 'object' to do this import.
    # We just need an interface that will return any paring errors as an XML structure.
    #

    # !!! Right now the parser framework doesn't support just passing in a filehandle.
    # !!! That's a shame.
    # !!! So I will create a temp file for the moment.
    #
    my $tmpname;
    my $tmpFH;
    do {
        $tmpname = tmpnam();
        $tmpname .= $fileName;
    } until $tmpFH = IO::File->new( $tmpname, O_RDWR | O_CREAT | O_EXCL );

    Common::Log::Debug("USING TMP FILE $tmpname");
    binmode($filehandle);
    while ( my $line = <$filehandle> ) {
        print $tmpFH $line;
    }

    seek( $tmpFH, 0, 0 );

    # !!! I have been led to believe that this will work...
    # !!! I have been led astray.
    #
    my $errors = Support::ArtistRoleMap::Importer->Import( filename => $tmpname );
    if ($errors) {
        Common::Log::Debug( "RETURNING ERRORS: " . Dumper($errors) );
        $self->{xml}{ImportErrors} = $errors;
    } else {

        # !!! Can't we use the canned Message class instead?
        #
        $self->{xml}{ImportSuccess} = 1;
    }
    unlink($tmpname) or die "ERROR - unable to unlink $tmpname: $!";

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

    return $response;
}

1;
