#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package Support::DataImport::Command::Main;
use strict;
use warnings;

use Data::Dumper;
use File::Path;
use File::Basename;

use lib '/app/tools/support/lib';
use Support::DataImport::DataImport;

use Support::DataImport::ImportTemplate;
use Support::DataImport::RPSDataImport;

use base 'Support::DataImport::Command::Base';

use lib '/app/tools/common/lib';
use RSApache::Response::XSLT;
use API::Response; # for JSON response

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

Log->init();
#Log->setLogLevel('debug');
Log->setLogLevel('debug');

sub cmd  { return ''; }
sub area { return 'import'; }

use constant kTemplate => "/app/tools/support/templates/dataimport/default.xsl";

my $gFilePath;

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

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

    my $client     = $self->getParam('clientid') || '';
    my $caseno     = $self->getParam('caseno')   || ''; # Ex. RSD-1234 or FB12345
    my $action     = $self->getParam('action')   || ''; # test, view_test, import, exceptions, upload
    my $nextAction = $self->getParam('nextaction') || '';
    my $file       = $self->getParam('filename') || '';
    my $importID   = $self->getParam('importID') || '';  # used for adding to existing import

    my $serviceID  = $self->getParam('serviceID') || '';
    my $versionNum = $self->getParam('versionNum') || '';
    my $filepath   = $self->getParam('filepath')  || '';

    my $clientID = (defined $client) ? $client : Common::RSApp::GetClientID();

    my $cdbo = Common::RSApp::GetCommonDB();

    if ( $action && $action eq 'validcase' ) {

        Log->info('Support::Command::Main - validcase');
        my $sql = "SELECT import_id FROM data_import WHERE case_id=". $cdbo->DBQuote($caseno);
        my $sth = $cdbo->DoCmd($sql);

        my %data = ( caseno => $caseno, status => '200', msg => 'ok' );

        my $statusCode = 200;
        my $msg = 'ok';
        if ( $sth->rows > 1 ) {
            $data{status} = 400;
            $data{msg} = 'case exists';
        }

        $response = API::Response->new(\%data);
        return $response;
    }

    #---------------------------------------------------------------------------
    # Get the data that will be used by the template to build the import tree
    #---------------------------------------------------------------------------
    $self->populateImportLists();

    if ( $action && $action eq 'analyze' ) {
        my $st;
        my %data = ( );
        if ( $file ) {

            # Upload file to server
            my $fh = $self->getCGI()->upload('filename');
            if ( $fh ) {
                eval { $self->uploadFile( $fh ); };

                if ( ref $@ ) {
                    die $@;
                }
            }

            # Now try to identify it
            $st = Support::DataImport::RPSDataImport->PreParse( "$gFilePath" );

            $data{filepath}   = $gFilePath;
            $data{filename}   = basename $gFilePath;
            $data{caseno}     = $caseno;
            $data{clientID}   = $clientID;
            $data{importID}   = $importID;
            $data{serviceID}  = $st->{service_id};
            $data{service}    = $st->{service};
            $data{versionNum} = $st->{version_num};
            $data{action}     = $nextAction;

            if ( $importID ) {
                my $import         = Support::DB::Item::DataImport->Lookup( import_id => $importID );

                my $_clientID      = $import->client_id;
                $data{clientID}    = $_clientID;

                my $client         = Common::DB::Item::Client->Lookup( client_id => $_clientID );
                $data{client_name} = $client->client_name;

                my $_serviceID        = $import->service_id;
                $data{parent_service} = Support::DataImport::RPSDataImport->GetTypeString($_serviceID);

                if ( $_serviceID != $st->{service_id} ) {
                    $self->{xml}{Collection}{analyze_error} = 'Template type mismatch';
                }

            }

        } else {
            $data{msg} = 'No file specified';
        }

        # Send params back for confirmation form
        $self->{xml}{ModalData} = \%data;
        $self->{xml}{Collection}{errstr} = $st->{errstr} if ( exists $st->{errstr} );

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

    Log->info("##### DataImport::Command::Main->execute  client($client) case($caseno) action($action) file($file)\n");

    # At this point, the action should be either 'upload' or 'add_new'
    # ('analyze' or 'validate' are handled above).
    # The file should already have been uploaded, analyzed and confirmed.

    my %args = (
        clientID   => $clientID,
        caseno     => $caseno,
        action     => $action,
        file       => $file,
        filePath   => $filepath,  # template temp filepath on server
        importID   => $importID,
        serviceID  => $serviceID,  # importer typeID
        versionNum => $versionNum,
    );

    #---------------------------------------------------------------------------
    # Once the file has been uploaded, we'll use ImportTemplate to handle it.
    # The 'action' parameter controls what is done with the file.
    #---------------------------------------------------------------------------
    if ( $clientID ) {
        my $status = new Support::DataImport::ImportTemplate( %args );
        Log->debug("Support/DataImport/Command/Main->execute: status = " . Dumper($status) );
        $self->{xml}{Collection} = $status;
    }

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

sub uploadFile {
    my $self = shift;
    my $fh   = shift;

    my $origFileName = $fh;
    $origFileName =~ s/.*[\/\\](.*)/$1/;

    # save the file to a working directory

    my $baseDir = '/app/shared/data_import';
    if ( ! -d $baseDir ) {
        Log->info("Support/DataImport/Command/Main->uploadFile: Creating baseDir $baseDir ...");
        mkpath($baseDir) or die "ERROR: unable to create path $baseDir: $!\n";
    }

    my $clientID = Common::RSApp::GetClientID();
    my $clientDir = $baseDir . "/$clientID";

    if ( ! -d $clientDir ) {
        Log->info("Support/DataImport/Command/Main->uploadFile: Creating clientDir $clientDir ...");
        mkpath($clientDir) or die "ERROR: unable to create path $clientDir $!\n";
    }

    my $finalFileName = $origFileName;
    my $finalFilePath = $clientDir . '/' . $finalFileName;

    Log->info("##### DataImport::Command::Main->uploadFile saving file to $finalFilePath ...");

    open( TMP, ">$finalFilePath" ) or die "couldn't write to disk";
    binmode(TMP);
    while (<$fh>) {
        print TMP;
    }
    close(TMP);

    if ( -e $finalFilePath ) {
        $gFilePath = $finalFilePath;
    } else {
        die RSApache::Message->new( type => 'error', code => "$origFileName|file_upload_saveerror $! $@" );
    }
}

1;
