#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::LabelContract::GroupTerm;

use strict;
use warnings;
use Carp;
use Data::Dumper;

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

use lib '/app/tools/rps/lib';
use RPS::LabelContract::GroupTermLabelHash;
use RPS::LabelContract::GroupTermExceptionHash;
use RPS::DB::Item::LabelContract;
use RPS::DB::Item::LabelContractGroupTerm;
use RPS::DB::Item::Label;

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{labelContractGroupTermID})
    {
        $self->_propertiesFromDB(\%properties, $args{labelContractGroupTermID});
    }
    else
    {
        $self->_propertiesFromDefaults(\%properties, $args{labelContractID});
    }

    $self->_initProperties(\%properties);
    $self->_initSubs(\%properties);

    return $self;
}


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

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


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

	$self->{_inDB} = 1;

    $hrProperties->{label_contract_group_term_id} = $dbItem->label_contract_group_term_id;
    $hrProperties->{priority} = $dbItem->priority;
    $hrProperties->{label_contract_id} = $dbItem->label_contract_id;
    $hrProperties->{distribution_fee} = $dbItem->distribution_fee;

    $hrProperties->{date_created} = $dbItem->date_created;
    $hrProperties->{date_modified} = $dbItem->date_modified;
    $hrProperties->{created_by} = $dbItem->created_by;
    $hrProperties->{modified_by} = $dbItem->modified_by;
    
    $hrProperties->{in_db} = $self->{_inDB};
}


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

    $self->{LabelContractGroupTermID}	 = Common::FormObject::Scalar->new(value => $props->{label_contract_group_term_id}, readOnly => 1);
    $self->{Priority} = Common::FormObject::Scalar->new(value => $props->{priority});    
    $self->{LabelContractID}		= Common::FormObject::Scalar->new(value => $props->{label_contract_id});
    $self->{DistributionFee}		= Common::FormObject::Scalar::Percent->new(value => $props->{distribution_fee}, required => 1);

    $self->{CreatedDate}		= Common::FormObject::Scalar::DateTime->new(value => $props->{date_created}, readOnly => 1);
    $self->{ModifiedDate}		= Common::FormObject::Scalar::DateTime->new(value => $props->{date_modified}, readOnly => 1);
    $self->{CreatedBy}			= Common::FormObject::Scalar::UserName->new(value => $props->{created_by}, readOnly => 1);
    $self->{ModifiedBy}			= Common::FormObject::Scalar::UserName->new(value => $props->{modified_by}, readOnly => 1);
    
    my $groupTermID = $props->{label_contract_group_term_id};
    $self->{GroupTermLabelList} = RPS::LabelContract::GroupTermLabelHash->new(labelContractGroupTermID => $groupTermID);
    $self->{GroupTermExceptionList} = RPS::LabelContract::GroupTermExceptionHash->new(labelContractGroupTermID => $groupTermID);

    $self->{InDB}	 = Common::FormObject::Scalar->new(value => $props->{in_db}, readOnly => 1);

    # ! Not sure if we're really going to delete these...
	# the default is 'OFF' (ie. don't delete)
	#
	#$self->{Delete} = Common::FormObject::Scalar::Boolean->new();
}


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

}


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

    $hrProperties->{label_contract_id} = $labelContractID;
}

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

	foreach my $field (qw(DistributionFee))
	{
		if (defined $self->$field())
		{
			$self->{_hasData} = 1;
		}
	}
	#if ($self->{_hasData})
	#{
	
	
	my $valid = $self->SUPER::validate();

    if (!$self->DistributionFee && $self->DistributionFee ne '0')
    {
        $self->{DistributionFee}->setError(Common::FormObject::kErrFieldBlank);
        $valid = 0;
    }	
	
	my $exceptionList = $self->GroupTermExceptionList();
	# Need to make sure that a combo of service and country is not duplicated in the same group term
    my %serviceCountryCombos;

    foreach my $exceptionID (keys %{$exceptionList->{GroupTermException}})
    {
        my $exception = $exceptionList->{GroupTermException}{$exceptionID};
		next if (!defined $exception);		
	    next if ($exception->Delete());
	
	    my $serviceID = $exception->ServiceID();
	    my $countryCode = $exception->CountryCode();
	    my $serviceCountryCombo = $serviceID . "-" . $countryCode;
	
        # We also want to check for dupes on the same contract.
        #
        if ($serviceCountryCombos{$serviceCountryCombo})
        {
            $exception->{ServiceID}->setError(Common::FormObject::kErrFieldDuplicate);
            $exception->{CountryCode}->setError(Common::FormObject::kErrFieldDuplicate);
            $valid = 0;
        } 
        else
        {
            $serviceCountryCombos{$serviceCountryCombo} = 1;
        }   		
	}
	
	my $labelList = $self->GroupTermLabelList();
	my $labelCount = 0;
    foreach my $termID (keys %{$labelList->{GroupTermLabel}})
    {
        my $term = $labelList->{GroupTermLabel}{$termID};

		next if (!defined $term);		
		
		next if ($term->Delete());
		next if (!$term->LabelID());

        $labelCount++;
	}

    if ($labelCount == 0) {
        $labelList->setError(Common::FormObject::kErrFieldBlank);
        $valid = 0;         
    }
	
    return $valid;
    
    
	#}
	#else
	#{
	#	return 1;
	#}
}

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

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

    return unless $self->{_hasData};


	my $dbObj;
	if($self->LabelContractGroupTermID())
	{
		$dbObj = RPS::DB::Item::LabelContractGroupTerm->Lookup(label_contract_group_term_id => $self->LabelContractGroupTermID());
        $dbObj->modified_by($self->ModifiedBy());
        $dbObj->date_modified(Common::DB::Item::kDateTimeNow);
	}
	else
	{
		$dbObj = RPS::DB::Item::LabelContractGroupTerm->Create();
        $dbObj->created_by($self->CreatedBy());
        $dbObj->date_created(Common::DB::Item::kDateTimeNow);
	}

	# set fields here
	#
	$dbObj->label_contract_id($self->LabelContractID());
    $dbObj->priority($self->Priority());
    $dbObj->distribution_fee($self->DistributionFee());

	# save db item
	#
	$dbObj->save();
	
	# save the label list
	#	
	foreach my $labelKey (keys %{$self->{GroupTermLabelList}->getHash()})
	{	
        my $label = $self->{GroupTermLabelList}->getHash()->{$labelKey};
		if(defined $label)
		{
			$label->LabelContractGroupTermID($dbObj->label_contract_group_term_id);
		}
	}

    $self->{GroupTermLabelList}->save();	
    
    
	# save the exception list
	#	
	foreach my $exceptionKey (keys %{$self->{GroupTermExceptionList}->getHash()})
	{	
        my $exception = $self->{GroupTermExceptionList}->getHash()->{$exceptionKey};
		if(defined $exception)
		{
			$exception->LabelContractGroupTermID($dbObj->label_contract_group_term_id);
		}
	}

    $self->{GroupTermExceptionList}->save();    
	

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

sub setDependency
{
	my $self = shift;
    $self->{HasDependency} = 1;
}

sub hasDependency
{
	my $self = shift;
    return $self->{HasDependency} ? 1 : 0;
}

sub delete
{
	my $self = shift;

	if($self->{_inDB})
	{
	    # First let's get rid of the labels associations.
	    $self->{GroupTermLabelList}->delete();
	    	    
	    # Next the exceptions.
	    $self->{GroupTermExceptionList}->delete();
	    
	    # And finally delete the group term itself.
		my $myDBObj = RPS::DB::Item::LabelContractGroupTerm->Lookup(label_contract_group_term_id => $self->LabelContractGroupTermID());
		$myDBObj->delete();
		
	}
    return 1;
}


###
1;#
###



