#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Distribution::Command::UploadFile;
use strict;
use warnings;

use lib '/app/tools/metadata/lib';
use Metadata::Importer;

use base 'RSApache::Command::XMLCommand';

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

use lib '/app/tools/appuser/lib';
use AppUser::DB::Item::AccessLevel;

sub cmd  { return 'upload_file'; }
sub area { return 'distribution'; }

use constant kTemplate => "";

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

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

    my $error = $self->_is_import_staged()
        ? "Another import is already staged."
        : $self->_import_metadata_file();

    return RSApache::Response::JSON->new($error);
}

sub _is_import_staged {
    my $importer = new Metadata::Importer( clientID => Common::RSApp::GetClientID() );
    return $importer->is_staged();
}

sub _import_metadata_file {
    my $self = shift;

    my $importer;
    my $import_fh   = $self->getCGI()->upload("fileUpload");
    my $import_file = $self->getParam("fileUpload");

    unless ( $self->getCGI()->upload("fileUpload") ) {
        return "File Required";
    }

    unless ( $import_fh && $import_file ) {
        return "Unable to read from input file.";
    }

    Common::Log::Debug("Uploading Metadata File: $import_file");

    $importer = new Metadata::Importer(
        clientID => Common::RSApp::GetClientID(),
        infile   => $import_file,
        fh       => $import_fh
    ) || die("Failed to create Metadata Controller");

    my $line_count = $importer->import_file();

    if ( $importer->errors() ) {
        Common::Log::Debug( join( ", ", $importer->errors() ) );
        return $importer->error_str();
    } else {
        Common::Log::Debug("   Import completed successfully");
        $importer->validate();
    }

    return '';
}

1;
