#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::Item::Payee;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Util qw(escape_mysql_regexp);
use Common::DB::ItemCollection;
use Common::DB::Item;
use Common::Assert;
use base 'Common::DB::Item';

use constant kDB => Common::DB::Item::kClientDB();

# This will need to be able to return payees from artist_payee, ca_publisher, publisher, and label_payee.

sub _config {
    my ($class) = @_;

    return {
        'name'            => {},
        'artist_payee_id' => {},
        'ca_publisher_id' => {},
        'publisher_id'    => {},
        'label_payee_id'  => {},
    };

}

sub Get {
    my ( $class, %args ) = @_;

    my @where;

    if ( $args{directOnly} ) {
        push @where, "is_admin = 0";
        push @where, "is_agency = 0";
        push @where, "(agent_id IS NULL || agent_id = 0)";
        push @where, "(admin_id IS NULL || admin_id = 0)";
    }

    if ( $args{adminOnly} ) {
        push @where, "is_admin = 1";
    }

    if ( $args{agentOnly} ) {
        push @where, "is_agency = 1";
    }

    if ( $args{withAdmin} ) {
        push @where, "(admin_id IS NOT NULL && admin_id <> 0)";
        push @where, "(agent_id IS NULL || agent_id = 0)";
    }

    if ( $args{withAgent} ) {
        push @where, "(agent_id IS NOT NULL && agent_id <> 0)";
    }

    # This is currenlty only used for the publisher queries.
    my $whereClause;
    if ( scalar @where ) {
        $whereClause = "WHERE " . join( ' AND ', @where );
    }

    my $sql;

    if ( $args{artistPayee} ) {
        $sql =
"SELECT artist_payee_id as artist_payee_id, NULL as ca_publisher_id, NULL as publisher_id, NULL as label_payee_id, name as name FROM artist_payee ";
    }

    if ( $args{artistPayee} && ( $args{caPublisher} || $args{publisher} || $args{labelPayee} ) ) {
        $sql .= "UNION ALL ";
    }

    if ( $args{caPublisher} ) {
        $sql .=
"SELECT NULL as artist_payee_id, ca_publisher_id as ca_publisher_id, NULL as publisher_id, NULL as label_payee_id, publisher_name as name FROM ca_publisher $whereClause ";
    }

    if ( $args{caPublisher} && ( $args{publisher} || $args{labelPayee} ) ) {
        $sql .= "UNION ALL ";
    }

    if ( $args{publisher} ) {
        $sql .=
"SELECT NULL as artist_payee_id, NULL as ca_publisher_id, publisher_id as publisher_id, NULL as label_payee_id, publisher_name as name FROM publisher $whereClause ";
    }

    if ( $args{publisher} && $args{labelPayee} ) {
        $sql .= "UNION ALL ";
    }

    if ( $args{labelPayee} ) {
        $sql .=
"SELECT NULL as artist_payee_id, NULL as ca_publisher_id, NULL as publisher_id, label_payee_id as label_payee_id, name as name FROM label_payee ";
    }

    $sql .= "ORDER BY name";

    return $class->GetAll($sql);
}

1;
