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

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

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

    my $dbo = Common::RSApp::GetClientDB();
    my $sql = "DELETE FROM " . kTable . " WHERE artist_royalty_statement_id = ?";
    $dbo->DoCmdWithPlaceholders($sql, [$statementID]);
}

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

    my $dbo = Common::RSApp::GetClientDB();
    my $sql = "DELETE FROM " . kTable . " WHERE album_id = ?";
    $dbo->DoCmdWithPlaceholders($sql, [$id]);
}

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

    #assert($albumID);
    assert($statementID);

    my $sql = "SELECT * FROM "
    . kTable
    . " WHERE album_id = "
    . $class->quote($albumID)
    . " AND artist_royalty_statement_id = "
    . $class->quote($statementID);

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

sub GetByAlbumStatementContract {
    my ( $class, $albumID, $statementID, $artistContractID ) = @_;

    assert($albumID);
    assert($statementID);
    assert($artistContractID);

    my $sql =
        "SELECT * FROM "
      . kTable
      . " WHERE album_id = "
      . $class->quote($albumID)
      . " AND artist_royalty_statement_id = "
      . $class->quote($statementID)
      . " and artist_contract_id = "
      . $class->quote($artistContractID);

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

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

    assert($statementID);

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

    my $sql = "SELECT IFNULL(SUM(revenue), 0) as revenue_sum, IFNULL(SUM(net_revenue), 0) as net_revenue_sum ";
    $sql .=   "FROM " . kTable . " WHERE artist_royalty_statement_id = " . $class->quote($statementID);

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

1;
