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

use File::Path;

use lib '/app/tools/rps/lib';
use RPS::Payor::Form;
use RPS::Payor::Command::Show;
use RPS::Command;
use RPS::CommandLog;
use base 'RPS::Command';

use lib '/app/tools/common/lib';
use Common::FormObject;
use RSApache::Response::XML;
use RSApache::Response::XSLT;
use RSApache::Response::Redirect;

sub cmd  { return 'edit'; }
sub area { return 'payor'; }

use constant kTemplate => "/app/tools/rps/templates/payor/index.xsl";

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

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

    my $payorID = $self->getParam('PayorID');
    my $form = RPS::Payor::Form->new( payorID => $payorID );

    if ( $self->getParam('formSubmit') ) {

        if ( $form->assignCGIParams( 'Form', $self->getParams() ) && $form->validate() ) {
            $form->save();

            RPS::CommandLog::Log( $self, $form->payorID() );

            # Check for an uploaded payor logo if Display Log is set to Yes.
            my $displayLogo = $self->getParam('Form_Payor_ShowLogo');
            my $imageError;
            my $logoUpdated = 0;

            if ( $displayLogo == 1 ) {
                my $fh = $self->getCGI()->upload('fileUpload');

                if ( defined $fh ) {
                    eval { $self->uploadLogo( $fh, $form->payorID() ); };

                    if ($@) {

                        # If this was an ErrorMessage exception, add the message to the redirect.
                        # Otherwise, re-throw it.
                        #
                        if ( ref $@ && $@->isa('RSApache::Message') ) {
                            $imageError = 1;
                            $form->setError(Common::FormObject::kErrFormSubmit);
                            $self->addMessageXML( type => "error", code => "invalid_format" );
                        } else {
                            die $@;
                        }
                    } else {
                        $logoUpdated = 1;    # Noting that we updated the logo, so we can display a messsage about it later.
                    }
                }
            }

            if ( !$imageError ) {

                # We want to change views, so we want to redirect to the Show command now.
                #
                my $successMessage = RPS::Message->new( type => "success", code => Common::FormObject::kSuccessFormSubmit );
                my %showParams = (
                    PayorID     => $form->payorID(),
                    msg         => $successMessage->toString(),
                    logoUpdated => $logoUpdated,
                );
                my $command = RPS::Payor::Command::Show->new(%showParams);
                return RSApache::Response::Redirect->new( $command->getRedirect() );
            }
        }
        else {
            $form->setError(Common::FormObject::kErrFormSubmit);
            $self->addMessageXML( type => "error", code => Common::FormObject::kErrFormSubmit );
        }
    }

    $self->{xml}{Form} = $form;

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

    return $response;
}

sub uploadLogo {
    my $self    = shift;
    my $fh      = shift;
    my $payorID = shift;

    my @validExtensions = RPS::Payor::Payor::kValidLogoExtensions;
    my @allowedUploadExtensions = grep { $_ ne 'png' } @validExtensions;

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

    my $ext = lc $origFileName;
    $ext =~ s/.*\.//;
    $ext = lc($ext);

    # Only allowing certain file extensions
    if ( !( grep /^$ext$/, @allowedUploadExtensions ) ) {
        die RSApache::Message->new( type => "error", code => "$origFileName|invalid_format" );
    }

    my $clientID = Common::RSApp::GetClientID();

    my $baseDir = "/app/tools/common/production/images/payor_logos";
    if ( !-d $baseDir ) {
        mkpath($baseDir) or die "ERROR: Unable to create path $baseDir: $!\n";
    }

    my $clientDir = $baseDir . "/$clientID";
    if ( !-d $clientDir ) {
        mkpath($clientDir) or die "ERROR: Unable to create path $clientDir: $!\n";
    }

    # Note that we are using the lower case version of the extentions when saving the file.
    my $finalFileName = $payorID . "." . $ext;
    my $finalFilePath = $clientDir . "/" . $finalFileName;

    # First delete any old logos we may have for this payor
    my $filePath = $clientDir . "/$payorID.";

    foreach my $ext (@validExtensions) {
        if ( -e $filePath . $ext ) {
            unlink $filePath . $ext;
        }
    }

    # Let's make sure it's gone.
    my $attempts = 0;
    foreach my $ext (@validExtensions) {
        while ( -e $filePath . $ext && $attempts < 10 ) {
            $attempts++;
            sleep(1);
        }
    }

    # Okay, now get to uploadin'
    print STDERR "UploadLogo: saving  upload to this location: $finalFilePath\n";

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

    # Let's make sure it's there
    $attempts = 0;
    while ( !-e $finalFilePath && $attempts < 10 ) {
        $attempts++;
        sleep(1);
    }

    if ( -e $finalFilePath ) {
        return 1;
    } else {
        die "Unable to save image to server";
    }
}

1;
