#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
package RPS::DB::Item::ArtistRoyaltyIncomeItem;
use strict;
use warnings;
use lib '/app/tools/common/lib';
use Common::Assert;
use Common::DB::Item;
use base 'Common::DB::Item';

use lib '/app/tools/rps/lib';
use RPS::DB::Item::ContractRateType;

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

sub DeleteByArtistRoyaltyAlbumID {
    my ( $class, $id ) = @_;
    assert($id);

    my $sql = "DELETE FROM " . kTable . " WHERE artist_royalty_album_id=$id";
    my $dbo = Common::RSApp::GetClientDB();
    $dbo->DoCmd($sql);
}

sub GetByArtistRoyaltyAlbumID {
    my ( $class, $id ) = @_;
    assert($id);

    my $sql = "SELECT * from " . kTable . " WHERE artist_royalty_album_id=$id";

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

sub GetIncomeSourcesByStatement {
    my ( $class, $id ) = @_;
    assert($id);

    # JPK - Changing this to a join to speed it up
    #
    my $sql =
        "SELECT DISTINCT income_source_id FROM "
      . kTable
      . " JOIN artist_royalty_album USING (artist_royalty_album_id) WHERE artist_royalty_statement_id = $id";

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

sub GetIncomeSourcesByStatementSkipNonPayable {
    my ( $class, $id ) = @_;
    assert($id);

#    my $sql = "SELECT DISTINCT income_source_id FROM " . kTable . " WHERE artist_royalty_album_id IN (SELECT artist_royalty_album_id FROM artist_royalty_album WHERE artist_royalty_statement_id = $id) AND contract_rate_type_id != " . RPS::DB::Item::ContractRateType::kRateTypeNonPayable;
    my $sql =
        "SELECT DISTINCT income_source_id FROM "
      . kTable
      . " JOIN artist_royalty_album USING (artist_royalty_album_id) WHERE artist_royalty_statement_id = $id"
      . " AND contract_rate_type_id != "
      . RPS::DB::Item::ContractRateType::kRateTypeNonPayable;

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

sub GetTotalsByStatementID {
    my ($class, $statementID) = @_;

    assert($statementID);

    my $dbo = Common::RSApp::GetClientDB();

    my $sql = "SELECT IFNULL(SUM(net_revenue), 0) as net_revenue_sum, IFNULL(SUM(total), 0) as total_sum ";
    $sql .=   "FROM " . kTable . " WHERE artist_royalty_album_id IN ";
    $sql .=     "( SELECT artist_royalty_album_id FROM artist_royalty_album ";
    $sql .=     "WHERE artist_royalty_statement_id = " . $class->quote($statementID) . ")";

    my $sth = $dbo->DoCmd($sql);
    my $hr  = $sth->fetchrow_hashref();
    return ( $hr->{net_revenue_sum}, $hr->{total_sum} );
}

1;
