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

use Data::Dumper;
use Carp;

use lib '/app/tools/rps/lib';

use RPS::DB::Item::PendingTransaction;

use lib '/app/tools/common/lib';
use Common::Debug;
use Common::Assert;
use Common::FormObject;
use base 'Common::FormObject';


sub _init
{
    my ($self, %args) = @_;

    $self->SUPER::_init(%args);

    my %properties;
    if ($args{_dbItem})
    {
        $self->_propertiesFromDBItem(\%properties, $args{_dbItem});
    }
    elsif ($args{transactionID})
    {
        $self->_propertiesFromDB(\%properties, $args{transactionID});
    }
    else
    {
        my $accountID = $args{accountID};
        $self->_propertiesFromDefaults(\%properties, $accountID);
    }

    $self->_initProperties(\%properties);

    return $self;
}


sub _propertiesFromDB
{
    my ($self, $hrProperties, $id) = @_;

    my $dbItem = RPS::DB::Item::PendingTransaction->Lookup(pending_transaction_id => $id);
    $self->_propertiesFromDBItem($hrProperties, $dbItem);
}


sub _propertiesFromDBItem
{
    my ($self, $hrProperties, $dbItem) = @_;

    $self->{_dbItem} = $dbItem;

    $hrProperties->{pending_transaction_id}     = $dbItem->pending_transaction_id;
    $hrProperties->{finance_account_id}         = $dbItem->finance_account_id;
    $hrProperties->{amount}                     = $dbItem->amount;
    $hrProperties->{memo}                       = $dbItem->memo;
    $hrProperties->{check_number}               = $dbItem->check_number;
    $hrProperties->{type_code}                  = $dbItem->type_code;
    $hrProperties->{currency_code}              = $dbItem->currency_code;
    $hrProperties->{date}                       = $dbItem->date;
    $hrProperties->{transaction_date}           = $dbItem->transaction_date;
}


sub _initProperties
{
    my ($self, $props) = @_;

    # Set the fields from the finance_account db item.
    #
    $self->{TransactionID}  = Common::FormObject::Scalar->new(value => $props->{pending_transaction_id}, readOnly => 1);
    $self->{AccountID}      = Common::FormObject::Scalar->new(value => $props->{finance_account_id});
    $self->{Memo}           = Common::FormObject::Scalar::String->new(value => $props->{memo});
    $self->{CheckNumber}    = Common::FormObject::Scalar::String->new(value => $props->{check_number});
    $self->{TypeCode}       = Common::FormObject::Scalar::String->new(value => $props->{type_code}, maxlength => 4, required => 1);
    $self->{CurrencyCode}   = Common::FormObject::Scalar::String->new(value => $props->{currency_code}, maxlength => 3);
    #$self->{Date}           = Common::FormObject::Scalar::DateTime->new(value => $props->{date});
    $self->{TransactionDate} = Common::FormObject::Scalar::Date->new(value => $props->{transaction_date});

    # this is how the template tells the backend to delete one of these.
    # the default is 'OFF' (ie. don't delete)
    $self->{Delete} = Common::FormObject::Scalar::Boolean->new();

    # Advances and Payments are stored as negative transactions, but displayed as positive.
    # So we need to convert the sign here at the last second.
    #
    my $amount = $props->{amount};
    if (RPS::DB::Item::PendingTransaction::kTypePayment == $self->TypeCode()
     || RPS::DB::Item::PendingTransaction::kTypeAdvance == $self->TypeCode())
    {
        $amount *= -1;
    }
    $self->{Amount} = Common::FormObject::Scalar::Decimal->new(value => $amount, precision => 0.2);
}


sub _propertiesFromDefaults
{
    my ($self, $hrProperties, $accountID) = @_;

    $hrProperties->{finance_account_id} = $accountID;
}

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

#    foreach my $field (qw(TypeCode Amount TransactionDate CheckNumber Memo))
    # !!! TypeCode is required, but I am relaxing the check for it since one of the forms
    # !!! is always hard-coding it.  Should think about changing that behavior.
    foreach my $field (qw(Amount TransactionDate CheckNumber Memo))
    {
        if($self->$field())
        {
            $self->{_hasData} = 1;
            last;
        }
    } 

    if ($self->{_hasData})
    {
        my $valid = $self->SUPER::validate();
        if ($valid)
        {
            # jpk - one more wrinkle.
            # If this is a payment or an advance, the value we store here in the XMLObject
            # must be >= 0.
            # Oddly, when we save the value, we'll store it as negative.
            # We can't do anything tricky in the initialization code, since TypeCode can be set dynamically.
            #
            if (RPS::DB::Item::PendingTransaction::kTypePayment == $self->TypeCode()
             || RPS::DB::Item::PendingTransaction::kTypeAdvance == $self->TypeCode())
            {
                if ($self->Amount() < 0)
                {
                    # !!! Set an error value here.
                    #
                    $self->{Amount}->setError(Common::FormObject::kErrFieldOutOfRange);
                    $valid = 0;
                }
            }
        }
        return $valid;
    }
    else
    {
        # If there is no data, I want to force-set the 'delete' flag.
        # This is basically to support the way the 'batch statement payment' screens work.
        #
        $self->Delete(1);
    }

    return 1;
}

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


    if ($self->Delete())
    {
        $self->delete();
        return;
    }

    if (! $self->{_hasData})
    {
        return;
    }

    # Don't bother unless we have an amount and a type code.
    #
    if (! $self->TypeCode() || $self->Amount() == 0)
    {
        return;
    }


    my $dbObj;
    if ($self->{_dbItem})
    {
        $dbObj = $self->{_dbItem};
    }
    else
    {
        $dbObj = RPS::DB::Item::PendingTransaction->Create();
    }

    assert($self->AccountID(), 'missing accountID');

    $dbObj->finance_account_id($self->AccountID());
    $dbObj->type_code($self->TypeCode());
    $dbObj->memo($self->Memo());
    $dbObj->check_number($self->CheckNumber());
    $dbObj->transaction_date($self->TransactionDate());

    # If we didn't specify a CurrencyCode, we'll default to the client's base currency.
    # !!! This may cause the DB::Item to blow up if this transaction gets applied to an 
    # !!! account with a different currency code...
    #
    #my $currencyCode = $self->CurrencyCode();
    #if (! $currencyCode)
    #{
    #   $currencyCode = Common::Client::Current()->Locale()->currencyFormat()->currencyCode();
    #}
    #$dbObj->currency_code($currencyCode);



    # Advances and Payments are stored as negative transactions, but displayed as positive.
    # So we need to convert the sign here at the last second.
    #
    my $amount = $self->Amount();
    if (RPS::DB::Item::PendingTransaction::kTypePayment == $self->TypeCode()
     || RPS::DB::Item::PendingTransaction::kTypeAdvance == $self->TypeCode())
    {
        $amount *= -1;
    }
    $dbObj->amount($amount);

    # save db item
    #
    $dbObj->save();

    # reload object
    #
    $self->_init(_dbItem => $dbObj);
}

sub delete
{
    my $self = shift; 

    if ($self->{_dbItem})
    {
        $self->{_dbItem}->delete();
    }

    return 1;
}


###
1;#
###
