#------------------------------------------------------------
# Copyright (C) 2012 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::Label::LabelWithUsers;

use strict;
use warnings;

use lib '/app/tools/appuser/lib';
use lib '/app/tools/common/lib';
use lib '/app/tools/rps/lib';
use RPS::DB::Item::Label;
use RPS::Label::UserList;
use AppUser::DB::Item::UserClientLabelMap;

use base 'RPS::Label::Label';

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

    $self->SUPER::_initProperties($props);

    my $labelID = $props->{label_id};
    if ($labelID) {

        # Making a full XML structure out of the list of users seems like total overkill to me.
        # All we want is their names.
        # However, I'm not totally clear yet as to exactly how we want to display these dudes.
        #
        # Rather than return a list in XML, I'll make the query here and construct a single string.
        #
        my @ids;
        my $allUsers = AppUser::DB::Item::UserClientLabelMap->GetAllForClientAndLabel( Common::RSApp::GetClientID(), $labelID );
        $self->{UserCount} = $allUsers->size();
        while ( my $user = $allUsers->next() ) {
            push @ids, $user->user_id;
        }
        $self->{UserID} = \@ids;

        # !!! Experiment with the whole list, too.
        # !!! THis is working, but not for the label edit form.
        # !!! so changing this around...
        #        $self->{Users} = RPS::Label::UserList->new(labelID => $labelID);
    }

    return $self;
}

# We need to whip up a custom accessor so we can let the CGI framework assign into our array reference.
# CGI will give us a simple scalar if there is just one value, but gives us an array reference if there are multiple.
#
sub UserID {
    my $self = shift;
    if (@_) {
        my $newVal = shift @_;
        if ( ref($newVal) eq 'ARRAY' ) {
            $self->{UserID} = $newVal;
        } else {
            $self->{UserID} = [$newVal];
        }
    } else {
        return $self->{LabelID};
    }
}

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

    # Call the inherited method first, so we'll have a label id set up.
    #
    my $dbObj = $self->SUPER::_save();

    # Delete the old user map (if any), and create the new one (if any)
    #
    AppUser::DB::Item::UserClientLabelMap->DeleteByLabelIDClientID( $dbObj->label_id, Common::RSApp::GetClientID() );
    foreach my $userID ( @{ $self->{UserID} } ) {
        my $newMapItem = AppUser::DB::Item::UserClientLabelMap->Create(
            user_id   => $userID,
            client_id => Common::RSApp::GetClientID(),
            label_id  => $dbObj->label_id(),
        );
        $newMapItem->save();
    }

    return $dbObj;
}

1;

